我想在std::map
中存储和识别std::function
对象。 确定我想使用std::function::target
。 如果我使用std::bind
绑定到类的成员函数,我无法从std::function::target
得到指针。C++ 11获取std :: function的指针
#include <functional>
#include <iostream>
using namespace std;
void normal_fun(int a)
{
std::cout << "hello\n"<<a;
}
class testclass
{
public:
int b;
void mytest(int a)
{
b = a;
}
};
uintptr_t getFuncAddress(std::function<void(int)> &f)
{
uintptr_t returnAddress = reinterpret_cast<uintptr_t>(f.target<void(*)(int)>());
return returnAddress;
}
int main()
{
testclass c;
std::function<void(int)> f1 = bind(&testclass::mytest,&c, placeholders::_1);
std::function<void(int)> f2 = normal_fun;
auto addrF1 = getFuncAddress(f1);
auto addrF2 = getFuncAddress(f2);
}
我该如何实现自己想做的事?
你不会在'std :: function'中存储实际的'void(int)',所以'target'返回一个'nullptr'。您存储绑定的结果,这是一些未知的函子类型。 – StoryTeller
这就是我所害怕的...你知道我怎么写'target'来获得绑定的指针? – bdahl
如果您需要这样做,我认为您正在接触错误的工具。 'std :: function'是关于类型擦除。试图通过类型来获取确切的目标有点像用'dynamic_cast's乱丢你的代码,而不是依赖于多态性。 – StoryTeller