Reputation: 111
this shouldn't be too hard but I am stuck.
I am trying to assign a function to a variable but I need to know the data type so I can assign it to a map.
I was successful doing this:
auto pfunc = Ext::SomeFunction
This will then allow me to do:
pfunc(arg, arg2);
But I need to know what data type is being covered by "auto" so I can map my functions to a string.
For example:
std::unordered_map<std::string, "datatype"> StringToFunc = {{"Duplicate", Ext::Duplicate}};
Most of these functions return void but there are other functions that returns double and int.
If there is a better way of doing this please let me know but I would really like to know the data type behind the auto as used above.
Thanks much for any help received.
Upvotes: 3
Views: 10540
Reputation: 111
I solved this by using the typedef and unordered_map below:
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}
};
Upvotes: 0
Reputation: 10415
Given a class foo
and a member function fun
, you can create a member function pointer in the following manner:
struct foo
{
void fun(int, float);
};
void(foo::*fptr)(int, float) = &foo::fun;
So the type of fptr
would be void(foo::*)(int, float)
. Usually with something like this you might want to introduce a typedef
or type alias to make the declaration more readable:
using function = void(foo::*)(int, float);
// or typedef void(foo::*function)(int, float);
function fptr = &foo::fun;
In addition, the above applies for member function pointers. For free functions the syntax would be:
void fun(int, float);
void(*fptr)(int, float) = &fun;
And you can define your type alias accordingly.
Upvotes: 7
Reputation: 16242
You need type erasure for function objects and std::function
implements that for you.
#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}};
}
Upvotes: 0