gpt4 book ai didi

c++ - 将重载函数传递给另一个函数时如何指定重载?

转载 作者:行者123 更新时间:2023-12-05 03:22:28 26 4
gpt4 key购买 nike

简单的例子:

std::vector<std::string> strings{"1","2","3");
std::vector<double> doubles(3);
transform(begin(strings), end(strings), begin(doubles), std::stod);

编译失败,因为编译器无法决定哪个 std::stod使用。需要 std::string 的那个或需要 std::wstring 的那个.我们看到只有一个会起作用 std::transform有效,但编译器无效。

选项(坏的)

  • 现在,我们不能std::stod<std::string>因为std::stod不是模板而是重载。即使它是一个模板,它也必须是一个带有静态非模板函数的类模板:Stod<std::string>::stod .
  • 我通常做的是使用 lambda:[](std::string const& s) { return std::stod(s); }但这是相当多的代码。
  • 还可以选择将重载函数转换为特定类型 ( double (*)(std::string const&) ),但为此,我必须知道返回类型。对于 std::stod这很简单,因为它总是返回一个简单的 double但对于其他功能来说,写下来可能是一件非常复杂的事情。

有没有比 lambda 更简洁的方法来选择正确的重载或诱使编译器自行解决?

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