我正在尝试将字符串转换为数字。为此,我找到了以下方法:
#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/