Hoorah Hoorah
Hoorah Hoorah

Reputation: 43

Template and function pointer confuse

I started learning c++ now. Im quite confuse about this definition. This is just a throwaway code as the actual implementation was on the book I was reading

class A
{
public:
    template<class T>
    void Hello(void(T::*func)())
    {
        func(); // Not working. Error term does not evaluate to function taking 0 argument
    }
};

class B
{
public:
     void funcA()
    {
        std::cout << "Hello world" << std::endl;
    }

    // This is called function pointers
    void funcB(void(*ptr)())
    {
        ptr();
    }
};

void main()
{
    A a;
    a.Hello(&B::funcA);


}

First is that what sort of template is that? If it's a template class shouldn't I delcare the template at the top of the class A?

Also why can't I call the func on Hello() like the same as calling a function pointer?

Upvotes: 1

Views: 74

Answers (1)

songyuanyao
songyuanyao

Reputation: 173014

First is that what sort of template is that? If it's a template class shouldn't I delcare the template at the top of the class A?

A::Hello is member function template.

Also why can't I call the func on Hello() like the same as calling a function pointer?

Because the parameter func of Hello is not a function pointer, but a member function pointer. You need an object to call on it. e.g.

template<class T>
void Hello(void(T::*func)())
{
    T t;
    (t.*func)();
}

LIVE

Upvotes: 1

Related Questions