Search code examples
c++functional-programmingstdbind

g++ error: ‘placeholders’ is not a namespace-name using namespace std::placeholders;


I am trying to understand std::bind.I have written the following program.

#include <memory>                                                                                                                                                                                                  
#include <functional>
#include <iostream>
#include <algorithm>

using namespace std::placeholders;

int add(int first,int second)
{
  return first + second;

}

bool divisible(int num, int den)
{
  if (num %den == 0)
    return true;
  return false;
}

int approach_1()
{
  int arr[10] = {1,20,13,4,5,6,10,28,19,15};
  int count = 0;

  for (int i = 0; i < sizeof(arr)/sizeof(int); i++)
  {
    if(divisible(arr[i],5))
      count++;
  }
}

int approach_2()
{
  int arr[10] = {1,20,13,4,5,6,10,28,19,15};
  return count_if(arr,arr + sizeof(arr)/sizeof(int), std::bind(divisible,_1,5));
}

For some reason my g++ compiler is not recognizing std::placeholders namesapce.

These are the errors that I get.

std_bind.cpp:6:22: error: ‘placeholders’ is not a namespace-name
 using namespace std::placeholders;
                      ^
std_bind.cpp:6:34: error: expected namespace-name before ‘;’ token
 using namespace std::placeholders;
                                  ^
std_bind.cpp: In function ‘int approach_2()’:
std_bind.cpp:36:54: error: ‘bind’ is not a member of ‘std’
   return count_if(arr,arr + sizeof(arr)/sizeof(int), std::bind(divisible,_1,5));
                                                      ^
std_bind.cpp:36:74: error: ‘_1’ was not declared in this scope
   return count_if(arr,arr + sizeof(arr)/sizeof(int), std::bind(divisible,_1,5));
                                                                          ^
std_bind.cpp:36:79: error: ‘count_if’ was not declared in this scope
   return count_if(arr,arr + sizeof(arr)/sizeof(int), std::bind(divisible,_1,5));
                                                                               ^
std_bind.cpp:36:79: note: suggested alternative:
In file included from /usr/include/c++/4.9/algorithm:62:0,
                 from std_bind.cpp:4:
/usr/include/c++/4.9/bits/stl_algo.h:3970:5: note:   ‘std::count_if’
     count_if(_InputIterator __first, _InputIterator __last, _Predicate __pred)
     ^

Solution

  • std::placeholders was added in C++11, so for g++ you must use a compiler switch that enables C++11 or later; such as -std=c++11 or -std=c++14.

    Often, g++ will mention in the error message when you tried to use a C++11 feature without using the right switch; but unfortunately this doesn't seem to be one of those times.