简体   繁体   中英

Need to assign function to variable in C++

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.

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.

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}};
}

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}
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM