Question

I'm confused by what's happening here and I was hoping that one of you gurus could help me understand. I've distilled this class to the methods that seem relevant, hopefully I didn't miss anything.

template < int* ( foo::*member_function )( void ) >
class bar
{
public:
    int myFunc( foo* myFoo )
    {
        int* result = ( myFoo->*member_function )();
        return *result;
    }
};

I don't understand how this has any idea what member_function is, there is no variable, yet it's being called, and someone help me out here?

Was it helpful?

Solution 2

member_function is the name of the template parameter given in:

template < int* ( foo::*member_function )( void ) >

That is, the template parameter member_function is a member function of foo that takes no arguments and returns an int*.

If an object of type bar is created with something like bar<&foo::a_member_function> b;, then the member_function template parameter is set to the member function foo::a_member_function. Then, when you call myFunc, passing it a pointer to a foo, it will call that member function on that foo.

OTHER TIPS

There are a limited number of kinds of data you can actually pass as template arguments; that is, not all template arguments need to be types:

[C++11: 14.1/1]: A non-type template-parameter shall have one of the following (optionally cv-qualified) types:

  • integral or enumeration type,
  • pointer to object or pointer to function,
  • lvalue reference to object or lvalue reference to function,
  • pointer to member,
  • std::nullptr_t.

You have shown an example of passing a pointer-to-member as a template argument.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top