我正在尝试std :: max。我正试图通过统一初始化(花括号)传递整数constexpr,以将它们与浮点变量进行比较。
实验a):使用double / int混合调用std :: max()
double a = 3.0;
int b = 5;
auto res = std::max(a, b);
不编译。lang报告error: no matching function for call to 'max'
。当然可以。
实验b):使用花括号+ constexpr int进行非锚转换
double a = 3.0;
constexpr int b = 5;
auto res = std::max(a, {b});
编译并按预期工作:返回值为5.0的double。
实验c):与b)相同,但交换std :: max的参数。
double a = 3.0;
constexpr int b = 5;
auto res = std::max({b}, a);
不能同时在gcc和clang下编译。为什么?
lang报告error: called object type 'double' is not a function or function pointer
。
存在这样的重载std::max
(来自cppreference.com):
template< class T, class Compare >
constexpr T max( std::initializer_list<T> ilist, Compare comp );
这auto res = std::max({b}, a);
比您的通话更合适
template< class T >
constexpr const T& max( const T& a, const T& b );
您正在尝试呼叫,因为{b}
可以推断std::initializer_list<int>
该调用具有两个参数精确匹配的转换级别,而你要拨打的过载需要一个转换从int
到double
这是不准确的匹配。
然后,将第二个参数视为Compare
要进行比较操作的函子,但double
显然调用a 失败。如果第二个参数不可调用,则不会禁用重载,这就是为什么仍然选择它。
不会发生这种情况auto res = std::max(a, {b});
,因为std::initializer_list
第二个参数没有参数的重载,因此只有您要调用的重载才是可行的。初始值设定项列表使第二个参数成为未推导的上下文,这就是为什么它与之相对的原因auto res = std::max(a, b);
,由于两个参数之间的模板参数推导不匹配而导致失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句