Windows MAX/MIN 宏作为模板
Windows MAX/MIN macros as templates
如果我要编写Windows min/max宏作为模板函数,正确的方法是什么?
最小宏定义为:
#define min(a, b) (((a) < (b)) ? (a) : (b))
我想一种选择是这样做:
template <typename T, typename U, typename R = std::common_type_t<T, U>>
constexpr R min(T const& a, U const& b) {
return std::min(static_cast<R>(a), static_cast<R>(b));
}
这是正确的和/或具有完全相同的行为吗?
std::min 不能使用,因为它期望两个参数属于同一类型。http://en.cppreference.com/w/cpp/algorithm/min
假设值a
和b
是算术类型,您可以执行以下操作:
#include <type_traits>
template <typename T, typename U>
constexpr auto min(T a, U b) -> typename std::common_type<T, U>::type {
// This is a lot cleaner in C++14 where we can use std::common_type_t and local
// variables in a constexpr function. Alternatively, you could just implement
// this by casting a and b to their common type and calling std::min.
return static_cast<typename std::common_type<T, U>::type>(a) <
static_cast<typename std::common_type<T, U>::type>(b) ?
static_cast<typename std::common_type<T, U>::type>(a) :
static_cast<typename std::common_type<T, U>::type>(b);
}
但是请注意,使用此方法具有隐藏强制转换的缺点,并且返回类型并不明显。例如,混合有符号和无符号参数可能会导致错误,如果你不小心和有意。
一般来说,我会重新评论只是使用 std::min
并根据需要强制转换类型(例如,如果a
是int
而b
是浮点数,只需执行std::min(static_cast<float>(a), b)
)。
相关文章:
- 关于 std::min, std::max 中的比较运算符的混淆
- 使用 CImg 库的 std::min 和 std::max 的编译问题
- 在f2c.h文件中定义min()max()宏时出错
- C++是否在 std::min 和 std::max 下标准化 std::optional 的行为?
- 执行 std::min(0.0, 1.0) 和 std::max(0.0, 1.0) 会产生未定义的行为
- 在调试中,如何知道对函数的重复调用中参数的统计数据(max-min,average,distribution..)
- C++试图在给定max/min x/y/z值、要在集合中的n个点和要递增的m个值的情况下生成每一组可能的点
- Windows MAX/MIN 宏作为模板
- 是否可以对"x = max(a,b); y = min(a,b);"进行微观优化?
- C++ 等同于 Matlab Max(find(array < x) 和 min(find(array > x)
- C++在数组中查找max(按行)和min(按列)元素
- uniform_int_distribution a(), b(), min(), and max()
- 当min和max为正数时,Rand()返回负数
- Max和Min用相同的元素堆
- std::min/max类型扣除在Linux和Windows上不同
- 有没有办法防止开发人员使用std::min, std::max
- 如何防止Gurobi将Max转换为Min问题
- 关于std::min()和std::max()的c++可变模板版本的思考
- MIN/MAX宏不能与visual studio一起工作
- 随机数生成器min和max-bounded,不工作