Windows MAX/MIN 宏作为模板

Windows MAX/MIN macros as templates

本文关键字:MAX MIN Windows      更新时间:2023-10-16

如果我要编写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

假设值ab是算术类型,您可以执行以下操作:

#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 并根据需要强制转换类型(例如,如果aintb是浮点数,只需执行std::min(static_cast<float>(a), b))。