如何将成员函数作为参数传递?
How to pass member function as a parameter?
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);
}
用法同上。
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 使用指向成员的指针将成员函数作为参数传递
- 是否有C++编译器选项允许激进地删除所有函数调用,并将参数传递给具有空体的函数
- 修改函数中的指针(将另一个指针作为参数传递)
- 将成员函数指针作为参数传递给模板方法
- 如何在C++中将迭代器作为函数参数传递
- 将附加参数传递给使用 beast::bind_front_handler 调用的函数
- 如何将一个类的函数作为另一个类的另一个函数的参数传递
- 如何传递带有通过引用传递的结构参数的函数?
- 如何在 c++ 中将函数作为参数传递?
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 将参数打包的参数传递到 std::queue 中,以便稍后使用不同的函数调用
- 为什么我不能将引用作为 std::async 的函数参数传递
- 如何在不使用指针的情况下将派生类的对象作为参数传递给基类中的函数?
- 将__device__ lambda 作为参数传递给 __global__ 函数
- 是否可以在不填充自己的参数的情况下将模板函数作为参数传递?
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 将函数作为参数传递以避免重复代码
- 如何在类(C )中作为参数传递函数