gpt4 book ai didi

c++ - 使用功能模板调用 C++ 类成员函数

转载 作者:行者123 更新时间:2023-11-30 02:37:15 32 4
gpt4 key购买 nike

我希望能够使用某种功能模板在类外部调用成员函数(例如 doSomething()testClass )。简而言之,能够以这种方式从 main() 中调用一个非静态成员函数,functionCaller(t.doSomething)

假设我有一个 C++ 类:

class testClass {
public:
testClass()
{
value = 0;
}
int prod(int i)
{
value *= i;
return value;
}
int doSomething()
{
value = prod(10);
return value;
}

private:
int value;
};

我的功能模板看起来像这样:

template<typename T, typename ret>
ret callFunction(T t, ret (T::*func)()) {

// checkSomePermissionsHere()
return t.func()
}

如果我尝试以下列方式使用此模板:

int main()
{
testClass t1;
callFunction(t1, &testClass::doSomething);
return 0;
}

我收到这个错误:

error: no member named 'func' in 'testClass'
return t.func(a);
^

通过 callFunction 方法在对象 t1 上调用此成员函数 (doSomething) 的正确方法是什么?我想将 callFunction 实现为通用 API 的一部分,它在执行提供的功能之前进行一些检查。

我正在为我的编译器使用 clang/LLVM 3.5。

最佳答案

改变这个:

return t.func()

为此:

return (t.*func)();

它应该可以正常编译和执行。


正如 Joachim Pileborg 所说,您可以使用 std::functionstd::bind .在这种情况下,您的代码可能如下所示:

#include <functional>
#include <iostream>

class EventHandler
{
public:
void addHandler(std::function<void()> callback)
{
std::cout << "Handler added..." << std::endl;
// Let's pretend an event just occured
callback();
}
};

class testClass {
public:
testClass()
{
value = 0;
EventHandler handler;
handler.addHandler(std::bind(&testClass::doSomething, this));
}
int doSomething()
{
value = prod(10);
std::cout << "I did something!\n";
return value;
}

private:
int value;
};

int main()
{
testClass t1;
return 0;
}

上面的代码是基于这个 answer .

关于c++ - 使用功能模板调用 C++ 类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31874531/

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