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

XNo*_*Nor 7 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;
}
Run Code Online (Sandbox Code Playgroud)

问题是我收到以下错误:

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

任何人都可以告诉我为什么我会收到这样的错误以及如何修复它?

先感谢您.

Pau*_*per 13

尝试

int b = stringToNumber<int>(a);
Run Code Online (Sandbox Code Playgroud)

由于T无法从任何参数推导出模板类型(在本例中std::string),因此需要明确定义它.