Swetas Swetas - 3 months ago 5
C++ Question

Use of std::function for function return

I came across C++11 style of function pointer using std::function method.Following scenario works fine with older method of function pointer but fails with new thingie.

#include <functional>
using namespace std;
function<int(int,int)> arithmeticFcn;

int add(int x,int y)
{
return x + y;
}

arithmeticFcn getOperation(char op)
{
switch (op) {
case '+':
return add;
break;
default:
return add;
break;
}
}

int main()
{
int x = 10,y = 20;
char op1;
cin >> op1;
arithmeticFcn Fcn = getOperation(op1);
cout << Fcn(x,y) << endl;
return 0;
}


Am i doing something wrong?

Answer

I'm going to go out on a limb and guess that you previously wrote:

typedef int arithmeticFcn(int, int);

and called this a function pointer.

It is not a function pointer. It was never a function pointer. You made arithmeticFcn a function type, which is how you were able to use it as you have done above.

But here:

function<int(int,int)> arithmeticFcn;

You are not creating a type. You are creating a functor, called arithmeticFcn.

I imagine you meant:

typedef function<int(int,int)> arithmeticFcn;