没有函数模板“max”的实例与参数列表匹配,参数类型为 (int, int)

pol*_*oig 3 c++ templates arguments

我刚刚开始使用 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;
}
Run Code Online (Sandbox Code Playgroud)

在cout的max中发现编译错误

谢谢你!

Art*_*cca 6

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;
}
Run Code Online (Sandbox Code Playgroud)

然而,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;
}
Run Code Online (Sandbox Code Playgroud)