没有函数模板的实例"max"与参数列表参数类型匹配(int、int)

No instance of function template "max" matches the argument list argument types are (int, int)

本文关键字:int 参数 类型 列表 函数模板 实例 max      更新时间:2023-10-16

我刚刚开始使用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;
}

您的函数需要两个 l 值引用,但是,您要传递的是两个 r 值。

传递两个变量或更改函数签名以接受 r 值引用。