c++ - 没有函数模板 "max"的实例匹配参数列表参数类型是 (int, int)

标签 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;
}

在cout的ma​​x中发现编译错误

谢谢!

最佳答案

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/

相关文章:

c# - 使 C# webmethod 的参数可选的最佳方法

c# - 如何在 C++ 中创建枚举类

c++ - 在此代码中调用赋值运算符的位置在哪里?

c++ - c++0x 元组是否使用新的可变参数模板或 Boost 的宏元组实现?

c++ - 使用模板对象的模板函数中无法识别的内容

powershell - 如何在命令行参数中正确地转义空格和反斜杠?

C++ 文件处理(结构)

wpf - 在 WPF 中覆盖模板化按钮的命令

c++ - 如何从数组构造元组

c++ - 作为成员函数的operator[] 的正确模板参数/参数是什么?