Bogdan
Bogdan

Reputation:

Can I send an operator as parameter to a function?

For example I can write in c:

int sum(int a, int b);
void print(int a, int b, int (*f)(int, int));

The question is can I send an operator?

print(12, 13, sum);
// print(12, 13, operator +); compilation error

Upvotes: 4

Views: 4103

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

Unfortunately, that’s not possible. There are wrappers for some common operators in the C++ standard library, in the functional header, e.g. std::plus<T>. It won’t work with your code though, since your print function requires a specific function parameter which plus<int> isn’t.

Instead of that, try passing a template argument, that works much better:

template <typename BinaryFunction>
void print(int a, int b, BinaryFunction f);

print(12, 13, std::plus<int>());

Upvotes: 12

MSalters
MSalters

Reputation: 179809

Yes, it's possible in general, but there's no int operator+(int, int). int+int happens to be a built-in expression. It would work for std::string::operator+

Upvotes: 2

Related Questions