Compile error with templates - no matching function for call

假装没事ソ 提交于 2019-12-09 12:24:32

问题


I'm trying to convert a string to a number. For that, I found the following way:

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

The problem is that I am getting the following error:

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

May anyone tell me why I am getting such error and how to fix it?

Thank you in advance.


回答1:


Try

int b = stringToNumber<int>(a);

Because the template type T can not be deduced from any of the parameters (in this case std::string) you need to explicitly define it.




回答2:


You haven't supplied a template argument. Note that in C++11, you can use std::stoi:

std::string a = "254";
int b = std::stoi(a);


来源:https://stackoverflow.com/questions/19882842/compile-error-with-templates-no-matching-function-for-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!