c++ - 使用模板编译错误 - 没有匹配的调用函数

标签 c++ templates type-conversion stdstring

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

#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;
}

问题是我收到以下错误:

error: no matching function for call to ‘stringToNumber(std::string&)’

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

提前谢谢你。

最佳答案

尝试

int b = stringToNumber<int>(a);

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

关于c++ - 使用模板编译错误 - 没有匹配的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19882842/

相关文章:

c++ - 将 std::result_of<> 用于成员类型的成员方法

mysql、预处理语句和自动类型转换

c++ - XERCESC 2.7 内存泄漏问题

c++ - 是否有 Mac OS X 相当于 Windows 的命名管道

c++ - 何时使用 if 语句选择多个循环而不是单个循环

c++ - 如何在 Windows 中用 c/c++ 将 double 类型写入文件?

c++ - std::remove_reference 有什么意义

c++ - CRTP 类示例

type-conversion - 将逻辑真/假转换为数字 1/0?

c++ - 隐式转换以匹配运算符参数