我有很多调用max(int,size_t)的代码; 有没有更聪明的方法来抑制这个错误?
它有点愚蠢,因为它适用于max(int,0)
我被允许这样做:size_t i = 0;
#include <algorithm>
int main()
{
size_t i = 2;
size_t m = std::max(i, size_t(2));
// size_t m = std::max(i, 2); error: no matching function for call to 'max(size_t&, int)'
}
答案 0 :(得分:3)
一般来说,我更喜欢std::max<size_t>(i, 2)
;它有类似的效果(实际上,它有点好,因为没有明确的演员,可能会使更多有趣的警告沉默)并避免使参数列表混乱。
另一种方法是编写自己的max
,接受不同类型的参数并返回&#34;更正&#34;常见类型(类似于使用宏完成):
template<typename T, typename U>
auto my_max(T t, U u) -> decltype(1?t:u){
return t>u?t:u;
}