Re: Using infix operators as argument for a function
Anton wrote:
#include <iostream>
using namespace std;
class MyClass{
public:
int test(int, int, int(*f)(int,int));
int add(int,int);
};
int MyClass::test(int i, int j, int (*func)(int,int)){
return func(i,j);
}
int add(int i, int j){return i+j;}
int main(){
MyClass mc;
// cout << mc.test(5,10,&add) << endl;
// cout << mc.test(5,10,&operator+) << endl;
// cout << mc.test(5,10,&(int::operator+)) << endl;
return 0;
}
What about a functor?
#include <iostream>
using namespace std;
class MyClass{
public:
template<typename O>
int test(int, int, O f);
};
template<typename O>
int MyClass::test(int i, int j, O f){
return f(i,j);
}
int main(){
MyClass mc;
cout << mc.test(5,10,std::plus<int>()) << endl;
return 0;
}
The second gets the following compiler error:
test.cpp: In function 'int main()':
test.cpp:24: error: no matching function for call to 'MyClass::test(int, int, <unresolved overloaded function type>)'
Well, taking the address of an overloaded function is something special.
test.cpp:12: note: candidates are: int MyClass::test(int, int, int (*)(int, int))
The third line gets another error:
test.cpp: In function 'int main()':
test.cpp:25: error: expected primary-expression before 'int'
test.cpp:25: error: expected `)' before 'int'
The operator + is a free function. Otherwise the implicit conversions
were non symmetric. Furthermore int is no class.
Is passing an infix operator as argument doable or do I need the wrap
around used in the fiorst line of main?
If the functor approach is not suitable to you, you need wrappers. But
beware, calling trivial operators through a function pointer may slow
down your application by a large factor, since the lookup for the right
operator is done at runtime each time. The functor on the other side is
as fast as if you had written i+j because everything is done at compile
time.
Marcel