Arn*_*aba 4 c++ overloading max initializer-list overload-resolution
我正在尝试使用max函数返回最大值,但它不适用于 3 个值。
代码块错误:
错误:“__comp”不能用作函数
编码:
#include <iostream>
using namespace std;
int main()
{
cout << max(5, 10, 20);
}
Run Code Online (Sandbox Code Playgroud)
Vla*_*cow 11
使用这个std::max接受类型对象的重载函数std::initializer_list<int>:
cout << max( { 5, 10, 20 } );
Run Code Online (Sandbox Code Playgroud)
这个函数有以下声明
template<class T>
constexpr T max(initializer_list<T> t);
Run Code Online (Sandbox Code Playgroud)
否则编译器会尝试选择函数
template<class T, class Compare>
constexpr const T& max(const T& a, const T& b, Compare comp);
Run Code Online (Sandbox Code Playgroud)
并发出错误。
请注意,您需要包含标题<algorithm>,