如何将成员函数作为参数传递? > C++语法正在扼杀我。 我试图将此+指针传递给成员函数: 因此,我做了以下工作: template <void(Myclass::*func)()> static void Myfunction(Myclass* theThis) { theThis->*func(); } 模板 静态void Myfunction(Myclass*theThis) { theThis->*func(); }
这很有效 但是现在我想从这个函数传递到另一个函数,这个成员函数如何将成员函数作为参数传递? > C++语法正在扼杀我。 我试图将此+指针传递给成员函数: 因此,我做了以下工作: template <void(Myclass::*func)()> static void Myfunction(Myclass* theThis) { theThis->*func(); } 模板 静态void Myfunction(Myclass*theThis) { theThis->*func(); },c++,templates,C++,Templates,这很有效 但是现在我想从这个函数传递到另一个函数,这个成员函数 template <void(Myclass::*func)()> static void Myfunction2(Myclass* theThis) // My new function { theThis->*func(); } template <void(Myclass::*func)()> static void Myfunction(Myclass* theThis) {
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
}
模板
静态void Myfunction2(Myclass*theThis)//我的新函数
{
theThis->*func();
}
模板
静态void Myfunction(Myclass*theThis)
{
Myfunction2(theThis)//这无法编译,模板参数可能不正确
}
但是它没有编译,我不知道如何传递这个成员函数
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:'::*'
编辑:
我只是想说清楚。
我没有名为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);
}
模板
静态void Myfunction2(Myclass*theThis)//我的新函数
{
(theThis->*func)();
}
模板
静态void Myfunction(Myclass*theThis)
{
Myfunction2(theThis);
}
我建议您根本不要使用指向成员函数的指针作为模板参数。相反,使用更简单的类型并传递该类型的可调用对象作为参数
这将允许您使用绑定到函数,或者使用,甚至是普通的非成员函数
也许是这样的:
template<typename C>
void MyFunction2(C callable)
{
callable();
}
template<typename C>
void MyFunction1(C callable)
{
MyFunction2(callable);
}
或
使用这样的模板是所有将可调用对象作为参数的标准库函数的常用方法
当然,您可以使用模板,也可以不使用模板:
void MyFunction2(std::function<void()> callable)
{
callable();
}
void MyFunction1(std::function<void()> callable)
{
MyFunction2(callable);
}
void MyFunction2(std::函数可调用)
{
callable();
}
void MyFunction1(std::函数可调用)
{
MyFunction2(可调用);
}
用法如上所述。可能重复:
theThis->*func()
也是错误的,应该是(theThis->*func)()代码>@Quentin你说得对
void MyFunction2(std::function<void()> callable)
{
callable();
}
void MyFunction1(std::function<void()> callable)
{
MyFunction2(callable);
}