gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:43:27 25 4
gpt4 key购买 nike

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

关于c++ - 如何将成员函数作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51245152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com