Alex Rivera | Logout

Operator as function pointer

Asked 2012-04-20T04:23:44.520
8

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) ()’

Edit
Report

1 Answer

1

One solution is provided by @In silico which is valid in both C++03 and C++11.

Here is another solution for C++11 only:

std::function<int(Test*)>  func;

func = &Test::DoIt1; 

func(this); //this syntax is less cumbersome compared to C++03 solution

A quick online full demo

answered 2012-04-20T04:46:19.933

Your Answer