Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass member function as a parameter?

Tags:

c++

templates

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

like image 362
OopsUser Avatar asked Sep 14 '26 17:09

OopsUser


2 Answers

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);
}
like image 91
Jarod42 Avatar answered Sep 16 '26 06:09

Jarod42


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.

like image 42
Some programmer dude Avatar answered Sep 16 '26 07:09

Some programmer dude



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!