简体   繁体   中英

How to pass member function as a parameter?

The C++ syntax is killing me. I'm trying to pass this + pointer to member function: So I did the following :

template <void(Myclass::*func)()>
static void Myfunction(Myclass* theThis)
{
    theThis->*func();
}

This works great.

But now I want to pass from this function to another function this member function.

template <void(Myclass::*func)()>
static void Myfunction2(Myclass* theThis) // My new function
{
    theThis->*func();
}

template <void(Myclass::*func)()>
static void Myfunction(Myclass* theThis)
{
    Myfunction2<&(Myclass::*func)>(theThis)  // This doesn't compile, the template parameter is probably incorrect
}

But it doesn't compile, I'm not sure how to pass this member function.

I get : error C2059: syntax error: '<tag>::*'

EDIT:

Just to make things clear. I don't have a function named func, this is just the name of the pointer to the member function

func is already the value you want to pass, so just pass it:

template <void(Myclass::*func)()>
static void Myfunction2(Myclass* theThis) // My new function
{
    (theThis->*func)();
}

template <void(Myclass::*func)()>
static void Myfunction(Myclass* theThis)
{
    Myfunction2<func>(theThis);
}

I suggest you don't use pointer-to-member functions as the template argument at all. Instead use a much simpler type and pass a callable object of that type as the argument.

This will allow you to use std::bind to bind to functions, or to use lambda expressions , or even normal non-member functions.

Perhaps something like this:

template<typename C>
void MyFunction2(C callable)
{
    callable();
}

template<typename C>
void MyFunction1(C callable)
{
    MyFunction2(callable);
}

To be used either like

MyFunction1(std::bind(&MyClass::TheRealFunction, theThis));

or

MyFunction1([&theThis]()
{
    theThis->TheRealFunction();
});

Using templates like that is the common way for all standard library functions taking callable objects as arguments.


You can of course use std::function , and then not use templates at all:

void MyFunction2(std::function<void()> callable)
{
    callable();
}

void MyFunction1(std::function<void()> callable)
{
    MyFunction2(callable);
}

Usage is as above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM