I would like to have a class implement operator() several different ways based on an option set in the class. Because this will be called a large number of times, I don’t want to use anything that branches. Ideally, the operator() would be a function pointer that can be set with a method. However, I’m not sure what this would actually look like. I tried:
#include <iostream>
class Test {
public:
int (*operator())();
int DoIt1() {
return 1;
}
int DoIt2() {
return 2;
}
void SetIt(int i) {
if(i == 1) {
operator() = &Test::DoIt1;
} else {
operator() = &Test::DoIt2;
}
}
};
int main()
{
Test t1;
t1.SetIt(1);
std::cout << t1() << std::endl;
t1.SetIt(2);
std::cout << t1() << std::endl;
return 0;
}
I know it will work if I create another function pointer and call that from the operator() function. But is it possible to have the operator() function itself be a function pointer? Something along the lines of what I posted (which doesn’t compile)?
The above code gives:
test.cxx:5:21: error: declaration of ‘operator()’ as non-function
test.cxx: In member function ‘void Test::SetIt(int)’:
test.cxx:17:16: error: ‘operator()’ not defined
test.cxx:19:16: error: ‘operator()’ not defined
test.cxx: In function ‘int main()’:
test.cxx:30:19: error: no match for call to ‘(Test) ()’
test.cxx:34:19: error: no match for call to ‘(Test) ()’
Your class needs to somehow remember what function pointer to use. Store it as a class member:
However, before you go into the effort of doing this, profile your code first and see if branching via
switchorifis actually a bottleneck (it might not be!). Modern processors have very counterintuitive performance characteristics, so compilers may be able to generate better code than you think it does. The only way to make sure that branching is actually too costly for you to use is to profile your code. (And by “profiling” I mean “run well-designed experiments”, not “come up with a hunch without testing”.)