加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 没有函数模板“max”的实例匹配参数列表参数类型是(int,int

发布时间:2020-12-16 10:07:40 所属栏目:百科 来源:网络整理
导读:我刚开始用c而且我没有很多关于模板的知识,我做了一个模板函数,我在Visual Studio中收到了这个错误: //没有函数模板“max”的实例匹配参数列表参数类型是(int,int) // C2664’T max(T,T)’:无法将参数1从’int’转换为’int’ #include "stdafx.h"#include
我刚开始用c而且我没有很多关于模板的知识,我做了一个模板函数,我在Visual Studio中收到了这个错误:

//没有函数模板“max”的实例匹配参数列表参数类型是(int,int)
// C2664’T max(T&,T&)’:无法将参数1从’int’转换为’int&’

#include "stdafx.h"
#include <iostream>

using namespace std;


template <class T>
T max(T& t1,T& t2)
{
    return t1 < t2 ? t2 : t1;
}
int main()
{
cout << "The Max of 34 and 55 is " << max(34,55) << endl;
}

复制错误发现在cout的最大值

谢谢!

解决方法

非const引用参数必须由实际变量支持(松散地说).这样可行:

template <class T>
T max(T& t1,T& t2)
{
    return t1 < t2 ? t2 : t1;
}
int main()
{
int i = 34,j = 55;
cout << "The Max of 34 and 55 is " << max(i,j) << endl;
}

但是,const引用参数没有此要求.这可能是你想要的:

template <class T>
T max(const T& t1,const T& t2)
{
    return t1 < t2 ? t2 : t1;
}
int main()
{
cout << "The Max of 34 and 55 is " << max(34,55) << endl;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读