gpt4 book ai didi

c++ - 返回具有自动返回类型的 std::function

转载 作者:行者123 更新时间:2023-12-01 14:36:34 25 4
gpt4 key购买 nike

我想创建一个仿函数来将 std::string 转换为不同的类型。

std::function<auto(const std::string)> create(const std::string &type)
{
if(type=="int") {
return [&](const std::string &value){return std::stoi(value);}
} else if(type=="float") {
return [&](const std::string &value){return std::stof(value);}
} else {
throw std::runtime_error("");
}
}

但似乎我们不能在这里使用 auto 作为 std::function 的返回类型。

有人可以建议一种方法吗?

最佳答案

对于一个函数或函数模板的一个实例,返回类型必须相同且固定。您可以将功能模板制作为

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("");
}
}

顺便说一句:作为返回类型,std::function 的参数应该是const std::string&。而且 lambda 似乎不需要捕获任何东西。

顺便说一句:根据您使用返回值的方式,直接返回 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("");
}
}

关于c++ - 返回具有自动返回类型的 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63277962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com