2013-11-09 75 views
5

我试图将字符串转换为数字。对于这一点,我发现下面的方法:编译模板错误 - 没有匹配的调用函数

#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&)’

五月谁能告诉我为什么我收到这样的错误,以及如何解决它?

预先感谢您。

+0

应该有更多的错误,喜欢的事实,'T'无法被推断。 – chris

+1

您可能需要'#include '将std :: stringstream放到您的作用域中。 –

+0

是的,我意识到一旦我修好了:) – XNor

回答

8

尝试

int b = stringToNumber<int>(a); 

由于模板类型T无法从任何参数来推断(在这种情况下std::string),你需要明确地定义它。

+0

我现在看到了,谢谢。 – XNor

+1

你的意思是推导*,而不是派生*。另外,C++ 11增加了'stoi','stol'等,所以使用'stringstream'就没有必要了。总是有'boost :: lexical_cast' – Praetorian

+0

@Praetorian,是正确的。 “派生”被添加到我的答案由别人。 –

0

您还没有提供模板参数。请注意,在C++ 11,你可以用std::stoi

std::string a = "254"; 
int b = std::stoi(a); 
相关问题