Say I have two overloaded function definitions:
int function_name(std::string);
int function_name(std::string, std::string);
I then use one of those functions as a parameter for a struct
struct My_struct
{
std::function<int(std::string)> function_name;
}
...
My_struct function_struct = { function_name };
This gives an error because the compiler has no way of knowing which function I intend to give it.
As seen in this post, How do I specify a pointer to an overloaded function?, pointed out by @FantasticMrFox below, one solution is to use static_cast like so:
static_cast<int(*)(std::string)>(function_name);
However, an alternative is to use a lambda like so:
My_struct function_struct = { [](std::string my_string) { return function_name(my_string); };
This also informs the compiler which version I intend to use.
Is there a better way to do this? Or some syntax I’m missing that does this in an easier way?
Edit:
After discussion in the comments, I edited this post to read more clearly as a comparison between function pointer and lambda.
>Solution :
It is slightly different to the case here: How do I specify a pointer to an overloaded function?
But it is quite similar, you want to get a std::function, but to achieve this you need to select the right function pointer. You will need to do this by informing the compiler which function to resolve with a static cast:
int function_name(std::string);
int function_name(std::string, std::string);
...
std::function<int(std::string)> f = static_cast<int(*)(std::string)>(function_name);
By defining the correct function pointer specifically you can create your std::function.
HOWEVER!
Write for readability first and you might be surprised by performance. For me personally seeing this:
My_struct function_struct = { [](std::string my_string) { return function_name(my_string); };
Is much clearer than this:
My_struct f = static_cast<int(*)(std::string)>(function_name);
Because you don’t need function pointers. And when you look at the disassembly of each you may be surprised to find that the lambda version may actually generate less assembly code because the compiler can do more tricky things with it.