Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 747
DBeck Avatar asked Jan 19 '26 18:01

DBeck


1 Answers

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.

like image 105
DeiDei Avatar answered Jan 21 '26 07:01

DeiDei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!