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.