我刚开始使用 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的max中发现编译错误
谢谢!
最佳答案
非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;
}
关于c++ - 没有函数模板 "max"的实例匹配参数列表参数类型是 (int, int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45792018/