我想在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