如何将成员函数作为参数传递?

How to pass member function as a parameter?

本文关键字:参数传递 函数 成员      更新时间:2023-10-16

C++语法正在杀死我。 我正在尝试传递this+指向成员函数的指针: 所以我做了以下工作:

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

这很好用。

但是现在我想从这个函数传递到另一个函数这个成员函数。

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
}

但是它不编译,我不确定如何传递这个成员函数。

我得到 :error C2059: syntax error: '<tag>::*'

编辑:

只是为了把事情说清楚。 我没有一个名为func的函数,这只是指向成员函数的指针的名称

>func已经是你想要传递的值,所以只需传递它:

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);
}

我建议你根本不使用指向成员的指针函数作为模板参数。而是使用更简单的类型,并将该类型的可调用对象作为参数传递。

这将允许您使用std::bind绑定到函数,或使用 lambda 表达式,甚至是普通的非成员函数。

也许是这样的:

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

用于以下任一

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

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

使用这样的模板是所有标准库函数将可调用对象作为参数的常用方法。


你当然可以使用std::function,然后根本不使用模板:

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

用法同上。