KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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) ()’
Tags (comma-separated)
Save Edits
Cancel