我想创建使用 stringstream
将字符串转换为数字的函数。如果我假设我的号码是 int
:
int stringToNumber(string str)
{
stringstream ss;
ss << str;
int num;
ss >> num;
return num;
}
cout << stringToNumber("182") + 100 << endl; //282
这段代码工作正常。但是当我尝试使用模板时出现错误。下面是我的代码:
template <typename number>
number stringToNumber(string str)
{
stringstream ss;
ss << str;
number num;
ss >> num;
return num;
}
错误:
main.cpp: In function ‘int main()’:
main.cpp:17:33: error: no matching function for call to ‘stringToNumber(const char [4])’
cout << stringToNumber("125") + 280 << endl;
^
main.cpp:17:33: note: candidate is:
main.cpp:6:8: note: template<class number> number stringToNumber(std::string)
number stringToNumber(string str)
^
main.cpp:6:8: note: template argument deduction/substitution failed:
main.cpp:17:33: note: couldn't deduce template parameter ‘number’
cout << stringToNumber("125") + 280 << endl;
最佳答案
您的模板参数不能以这种方式推导。您必须明确提供模板参数:
std::cout << stringToNumber<int>("125");
关于c++ - 模板和字符串流的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23714207/