Simple example:
std::vector<std::string> strings{"1","2","3");
std::vector<double> doubles(3);
transform(begin(strings), end(strings), begin(doubles), std::stod);
This fails to compile because the compiler cannot decide which std::stod
to use. The one that takes an std::string
or the one that takes an std::wstring
. We see that only one would work given how std::transform
works, but the compiler doesn't.
Options (bad ones)
- Now, we cannot say
std::stod<std::string>
becausestd::stod
is not a template but an overload. And even if it was a template, it would have to be a class template with a static non-templated function:Stod<std::string>::stod
. - What I usually do is use a lambda:
[](std::string const& s) { return std::stod(s); }
but that is quite a lot of code for nothing. - There is also the option to cast the overloaded function to the specific type (
double (*)(std::string const&)
) but to do that, I have to know the return type. Forstd::stod
that is simple, because it always returns a simpledouble
but for other functions that might be a very complicated thing to write down.
Is there a more concise way than the lambda to select the correct overload or trick the compiler into figuring it out itself?