0
votes

I want to achieve the following:

template <typename F>
class MyTemplate {
public:
    void SomeMethod(F f) {
        //...
    }

    template <typename C, typename O>
    void SomeMethod(C::*F f, O& o) {    // this does not work, I want a member function pointer here
        //...
    }
};

static void StaticFunction(int);

class SomeClass {
public:
    void MemberMethod(int);
};


MyTemplate<void(int)> mt;
mt.SomeMethod(StaticFunction);
SomeClass SomeClassInstance;
mt.SomeMethod(&SomeClass::MemberMethod, SomeClassInstance); // I want to call it like this

I want to create a template with a function type parameter. The template should 'create' overloads for C-style or static function pointers as well as members functions. How can I create the member function type from the free function type that should be used to declare the template instance?

I want to be able to use the template with types like:

  • void(void)
  • void(int)
  • int(void)
  • int(int)
  • int(int, int, int, int)
  • void(int, int, int, int)
  • etc.
1
I think you mean template <typename C, typename O> void SomeMethod(F C::* f, O& o); Note the placement of F. Live exampledyp
You should at least make an effort to write code that is correct except for the one thing you don't know how to do. This is sloppy. No class before the declaration of SomeClass, no semicolons after class definitions... and there's no declaration of MyClass (I guess you meant SomeClass)Brian Bi
@dyp You should make that an answer.Brian Bi
@dyp: That syntax is new to me. Does it have a name?Nemo
@Nemo F C::* f? "Pointer to member function of class C returning F". F is void, C is MyClass.Peter - Reinstate Monica

1 Answers

1
votes

Here is the answer provided by dyp:

template <typename F>
class MyTemplate {
public:
    void SomeMethod(F f) {
        //...
    }

    template <typename C, typename O>
    void SomeMethod(F C::* f, O& o) {    // this does work
        //...
    }
};

static void StaticFunction(int) {}

struct SomeClass {
public:
    void MemberMethod(int) {}
};

int main()
{
    MyTemplate<void(int)> mt;
    mt.SomeMethod(StaticFunction);
    SomeClass SomeClassInstance;
    mt.SomeMethod(&SomeClass::MemberMethod, SomeClassInstance); // I want to call it like this
}