Paster Keller
Paster Keller

Reputation: 33

Member function calling - can I access it without an object?

If I have something like

class MyClass
{
public:
    void callMe()
    {
        cout << "called";
    }
};

template< void (MyClass::*callFunc)() > struct A 
{
   void A_call()
   {
       callFunc();
   }
};

int main(int argc, char *argv[])
{
   struct A <&MyClass::callMe> object;

   object.A_call();
}

This doesn't compile since it says "callFunc: term does not evaluate to a function taking 0 arguments".

Isn't a class member function a compile-time constant?

Upvotes: 1

Views: 110

Answers (3)

Jerry Coffin
Jerry Coffin

Reputation: 490048

You've defined callFunc as a pointer to a member function. To dereference it (call the member function) you need to supply both the pointer itself and an object whose member you're going to call, something along this general line:

template <void (MYClass::*callFunc)() > class A { 
    MyClass &c;
public:
    A(MyClass &m) : c(m) {}
    void A_call() { c.*callFunc(); }
};

int main() { 
    MyClass m;

    A<&MyClass::callMe> object(m);

    object.A_call();
};

Upvotes: 1

MFH
MFH

Reputation: 1734

MyClass::callMe

is a non-static member function! You can't call it without an instance of MyClass! The instance is passed as first argument, therefor MyClass::callMe is actually:

void callMe(MyClass * this)

which obviously can't be called without an instance of MyClass...

Upvotes: 0

niculare
niculare

Reputation: 3687

You call the method callFunc() outside of the class MyClass and it is not static, then you will need an instance of MyClass to call it.

Upvotes: 0

Related Questions