对于一个函数或函数模板的一个实例化,返回类型必须相同且固定。您可以将函数模板设为
template <typename R>
std::function<R(const std::string&)> create()
{
if(std::is_same<R, int>::value) {
return [](const std::string &value){return std::stoi(value);};
} else if(std::is_same<R, float>::value) {
return [](const std::string &value){return std::stof(value);};
} else {
throw std::runtime_error("");
}
}
然后像这样使用它
auto f_int = create<int>();
auto f_float = create<float>();
由于 C++17 可以使用constexpr if,不必要的语句将在编译时被丢弃。
template <typename R>
std::function<R(const std::string&)> create()
{
if constexpr (std::is_same_v<R, int>) {
return [](const std::string &value){return std::stoi(value);};
} else if constexpr (std::is_same_v<R, float>) {
return [](const std::string &value){return std::stof(value);};
} else {
throw std::runtime_error("");
}
}
BTW:作为返回类型,std::function 的参数应该是const std::string&。而且 lambda 似乎不需要捕获任何东西。
BTW2:根据您使用返回值的方式,直接返回 lambda 而不是将其包装到 std::function 中也可能就足够了。
template <typename R>
auto create()
{
if constexpr (std::is_same_v<R, int>) {
return [](const std::string &value){return std::stoi(value);};
} else if constexpr (std::is_same_v<R, float>) {
return [](const std::string &value){return std::stof(value);};
} else {
throw std::runtime_error("");
}
}