tags:

views:

123

answers:

1

Hi, this is my code:

#include <iostream>
#include <functional>

using namespace std;

int main() {
  binary_function<double, double, double> operations[] = {
    plus<double>(), minus<double>(), multiplies<double>(), divides<double>() 
  };
  double a, b;
  int choice;
  cout << "Enter two numbers" << endl;
  cin >> a >> b;
  cout << "Enter opcode: 0-Add 1-Subtract 2-Multiply 3-Divide" << endl;
  cin >> choice;
  cout << operations[choice](a, b) << endl;
}

and the error I am getting is:

Calcy.cpp: In function ‘int main()’:
Calcy.cpp:17: error: no match for call to ‘(std::binary_function<double, double, double>) (double&, double&)’

Can anyone explain why I am getting this error and how to get rid of it?

+3  A: 

std::binary_function only contains typedefs for argument and return types. It was never intended to act as a polymorphic base class (and even if it was, you'd still have problems with slicing).

As an alternative, you can use boost::function (or std::tr1::function) like this:

boost::function<double(double, double)> operations[] = {
  plus<double>(), minus<double>(), multiplies<double>(), divides<double>() 
};
UncleBens
Why doesn't the compiler flag an error on the first line of `main()`? If that array definition is allowed, so should be the calls to the functions stored in the array. Why that error then?
Venkat Shiva
It just does what you require it to do. `binary_function` (or for what matters any other type in the standard library) don't deserve special treatment from the compiler. Since `plus`... do inherit from `binary_function` the assignment is correct and you get slicing. The compiler fails to compile the last line as `double operator()(double,double)` is not defined in `binary_function`, just as calling any method added in a derived class through a base would fail...
David Rodríguez - dribeas
@David: Alright, I understood it now. Thanks. Post it as answer and I will accept it.
Venkat Shiva
Just accept this one. It is complete and if more detail is needed people can just read the comments (that you can also 'upvote' to make them more visible)
David Rodríguez - dribeas
@David: Okay, fine. Thanks again.
Venkat Shiva