使用模板编译错误 - 没有匹配的调用函数 [英] Compile error with templates - no matching function for call

查看:31
本文介绍了使用模板编译错误 - 没有匹配的调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字符串转换为数字.为此,我找到了以下方法:

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:

错误:没有匹配的函数调用‘stringToNumber(std::string&)’

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?

提前致谢.

推荐答案

尝试

int b = stringToNumber<int>(a);

因为模板类型 T 不能从任何参数中推导出来(在本例中为 std::string),您需要明确定义它.

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.

这篇关于使用模板编译错误 - 没有匹配的调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆