c++ - 模板和字符串流的问题

标签 c++

我想创建使用 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/

相关文章:

c++ - 处理构造函数时的智能指针

c++ - 写入文件和 mkdir 竞争条件 C

c++ - 编译 cpp 文件时出错 (ros)

c++ - 如何使用 ifstream 将任何自定义数据类型写入文件?

c++ - 自定义Allocator编译难点2

c++ - 从注册表中读取值 C++

c++ - 编译第一个 mathgl 示例错误

c++ - 来自视频文件的垫子数组 - opencv

c++ - 堆栈和堆上的 STL 容器

c++ - 在代码大纲中隐藏成员元素的类名