Can I send an operator as a 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 
+4
source share
2 answers

Unfortunately this is not possible. There are wrappers for some common operators in the C ++ standard library in the functional header, for example. std::plus<T> . However, it will not work with your code, since your print function requires a specific function parameter, which plus<int> isnt.

Instead, 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>()); 
+11
source

Yes, it is possible at all, but there is no int operator+(int, int) . int+int turns out to be an inline expression. It would work on std::string::operator+

+2
source

All Articles