需要在 C++ 中将函数分配给变量
Need to assign function to variable in C++
这不应该太难,但我卡住了。
我正在尝试将一个函数分配给一个变量,但我需要知道数据类型以便我可以将它分配给一个映射。
我这样做成功了:
auto pfunc = Ext::SomeFunction
这将允许我做:
pfunc(arg, arg2);
但我需要知道 "auto" 涵盖的数据类型,以便我可以将函数映射到字符串。
例如:
std::unordered_map<std::string, "datatype"> StringToFunc = {{"Duplicate", Ext::Duplicate}};
这些函数中的大多数 return 无效,但还有其他函数 return 是双精度和整数。
如果有更好的方法,请告诉我,但我真的很想知道上面使用的 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}
};
这不应该太难,但我卡住了。
我正在尝试将一个函数分配给一个变量,但我需要知道数据类型以便我可以将它分配给一个映射。
我这样做成功了:
auto pfunc = Ext::SomeFunction
这将允许我做:
pfunc(arg, arg2);
但我需要知道 "auto" 涵盖的数据类型,以便我可以将函数映射到字符串。
例如:
std::unordered_map<std::string, "datatype"> StringToFunc = {{"Duplicate", Ext::Duplicate}};
这些函数中的大多数 return 无效,但还有其他函数 return 是双精度和整数。
如果有更好的方法,请告诉我,但我真的很想知道上面使用的 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}
};