Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::bind

I'm trying to implement the std::bind in an easy example:

#include <functional>
#include <iostream>
using namespace std;
using namespace std::placeholders;
int multiply(int a, int b)
{
    return a * b;
}
int main()
{
    auto f = bind(multiply, 5, _1);
    for (int i = 0; i < 10; i++)
    {
        cout << "5 * " << i << " = " << f(i) << endl;
     }
    return 0;
}

however, when I compile this is what I get:

test.cpp:5: error: ‘placeholders’ is not a namespace-name
test.cpp:5: error: expected namespace-name before ‘;’ token
test.cpp: In function ‘int main()’:
test.cpp:14: error: ISO C++ forbids declaration of ‘f’ with no type
test.cpp:14: error: ‘_1’ was not declared in this scope
test.cpp:14: error: ‘bind’ was not declared in this scope
test.cpp:17: error: ‘f’ cannot be used as a function

awkward when a given example returns compilation errors o.O

thank you in advance for your help

like image 542
Gigi Borino Avatar asked Jan 27 '14 12:01

Gigi Borino


1 Answers

Your code compiles fine as long as -std=c++11 switch is passed to gcc, and with the November CTP compiler release of Visual Studio 2013.

Here's a sample command line compilation for your code:

g++-4.8 -std=c++11 -O2 -Wall -pedantic main.cpp

Consult How to use g++ in terminal in mac? to read about your options - invoking under xcode or directly.

like image 72
mockinterface Avatar answered Oct 15 '22 06:10

mockinterface