[英]Need to assign function to variable in C++
這不應該太難,但是我被困住了。
我正在嘗試將函數分配給變量,但是我需要知道數據類型,以便可以將其分配給映射。
我成功做到了:
auto pfunc = Ext::SomeFunction
然后,這將允許我執行以下操作:
pfunc(arg, arg2);
但是我需要知道“自動”包含的數據類型,以便可以將函數映射到字符串。
例如:
std::unordered_map<std::string, "datatype"> StringToFunc = {{"Duplicate", Ext::Duplicate}};
這些函數大多數返回void,但是還有其他函數返回double和int。
如果有更好的方法,請告訴我,但我真的很想知道上面使用的auto后面的數據類型。
非常感謝您提供的任何幫助。
給定一個class foo
和一個成員函數fun
,您可以按以下方式創建成員函數指針:
struct foo
{
void fun(int, float);
};
void(foo::*fptr)(int, float) = &foo::fun;
因此, fptr
的類型為void(foo::*)(int, float)
。 通常使用類似這樣的內容,您可能想要引入typedef
或類型別名,以使聲明更具可讀性:
using function = void(foo::*)(int, float);
// or typedef void(foo::*function)(int, float);
function fptr = &foo::fun;
另外 ,以上適用於成員函數指針。 對於免費功能,語法為:
void fun(int, float);
void(*fptr)(int, float) = &fun;
您可以相應地定義類型別名。
您需要為函數對象提供類型擦除,而std::function
會為您實現它。
#include<functional>
#include<unordered_map>
... define f1
... define f2
int main(){
std::unordered_map<std::string, std::function<ret_type(arg1_type, arg2_type)>> um = {{"name1", f1}, {"name2", f2}};
}
我通過使用下面的typedef和unordered_map解決了這個問題:
typedef void(*StringFunc)(std::basic_string<char, std::char_traits<char>, std::allocator<char> >);
std::unordered_map<std::string, StringFunc> StringToAction = {
{"Buy", Car::BuyCar}, {"Fix", Car::FixCar}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.