KevinD
KevinD

Reputation: 69

C++ Pointer to member function, member

I want to have a member that is a pointer to member function. Then I can set this pointer to point at one of the other member functions and use it to call the function I really want. Essentially I have different ways to implement a function and I want to set a pointer to call the appropriate one. Also the class is a template class.

I can't find a way call the function via the function pointer. For example:

template <typename T> class C
{
public:
    typedef void(C<T>::*Cfunc)(int);
    Cfunc cf;
    void p1(int i) {
    }
    C (int i)
    {
        cf = &C<T>::p1;
    }
};
int main ()
{
C<int> Try1(1);
(Try1.*C<int>::cf)(10);
 return 0;
}

I get the error:

tc.cpp: In function ‘int main()’:
tc.cpp:5:11: error: invalid use of non-static data member ‘C<int>::cf’
     Cfunc cf;
           ^
tc.cpp:16:16: error: from this location
 (Try1.*C<int>::cf)(10);

Upvotes: 2

Views: 162

Answers (1)

Marco A.
Marco A.

Reputation: 43662

Your pointer to member function is not a static variable and therefore you need an instance of C to access it

int main()
{
  C<int> Try1(1);
  (Try1.*Try1.cf)(10);
  return 0;
}

Upvotes: 7

Related Questions