【问题标题】:Compile error with templates - no matching function for call使用模板编译错误 - 没有匹配的调用函数
【发布时间】:2013-11-21 20:48:22
【问题描述】:

我正在尝试将字符串转换为数字。为此,我找到了以下方法:

#include <iostream>
#include <string>

template <typename T>
T stringToNumber(const std::string &s)
{
    std::stringstream ss(s);
    T result;
    return ss >> result ? result : 0;
}

int main()
{
    std::string a = "254";
    int b = stringToNumber(a);

    std::cout << b*2 << std::endl;
}

问题是我收到以下错误:

错误:没有匹配的函数调用'stringToNumber(std::string&)'

谁能告诉我为什么会出现这样的错误以及如何解决?

提前谢谢你。

【问题讨论】:

  • 这个错误应该更多,比如T不能被推断出来。
  • 您可能还需要在顶部 #include &lt;sstream&gt; 才能将 std::stringstream 纳入您的范围。
  • 是的,我一修好就意识到 :)

标签: c++ templates type-conversion stdstring


【解决方案1】:

试试

int b = stringToNumber<int>(a);

因为模板类型T不能从任何参数(在本例中为std::string)推导出来,您需要显式定义它。

【讨论】:

  • 您的意思是推导,而不是派生。此外,C++11 添加了stoistol 等,因此不需要使用stringstream。而且总是有boost::lexical_cast
  • @Praetorian,正确。 “派生”已被其他人添加到我的答案中。
  • @Paul 抱歉,我之前使用的是手机,并没有同时查看编辑历史记录。
【解决方案2】:

您没有提供模板参数。请注意,在 C++11 中,您可以使用 std::stoi:

std::string a = "254";
int b = std::stoi(a);

【讨论】:

    猜你喜欢
    • 2017-09-26
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 2022-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多