gpt4 book ai didi

c++ - MSVC2017 上的 SFINAE 与 numeric_limits::max()

转载 作者:行者123 更新时间:2023-12-02 12:51:21 25 4
gpt4 key购买 nike

以下代码:

template <typename T, typename U>
typename std::enable_if<
std::numeric_limits<T>::max() == std::numeric_limits<U>::max(),
bool>::type
same_max() {
return true;
}

template <typename T, typename U>
typename std::enable_if<
std::numeric_limits<T>::max() != std::numeric_limits<U>::max(),
bool>::type
same_max() {
return false;
}

无法在 MSVC2017 上编译(在 gcc/clang 上正常),并出现以下错误:

error C2995: 'std::enable_if<,bool>::type same_max(void)': function template has already been defined

这是我的 SFINAE 的问题,还是 MSVC 中的错误?

注意:使用std::numeric_limits<T>::is_signed (或 std::is_signed<T>::value )而不是 std::numeric_limits<T>::max()编译良好:

template <typename T, typename U>
typename std::enable_if<
std::is_signed<T>::value == std::is_signed<U>::value,
bool>::type
same_signedness() {
return true;
}

template <typename T, typename U>
typename std::enable_if<
std::is_signed<T>::value != std::is_signed<U>::value,
bool>::type
same_signedness() {
return false;
}

最佳答案

这看起来绝对像是编译器中的错误。它不接受 SFINAE 中的成员函数(请注意,问题中的代码不仅对于 min()/max() 失败,而且对于像 min()/max() 这样的任何成员函数都失败code>epsilon()lowest()),但它确实接受成员常量。您可以使用以下简单的解决方法,并使用 struct 进行额外的间接级别(如果仅限于 C++11):

template<typename T>
struct get_max {
static constexpr T value = std::numeric_limits<T>::max();
};

template <typename T, typename U>
typename std::enable_if<get_max<T>::value == get_max<U>::value, bool>::type
same_max() {
return true;
}

template <typename T, typename U>
typename std::enable_if<get_max<T>::value != get_max<U>::value, bool>::type
same_max() {
return false;
}

或变量模板 (C++14 起):

template<typename T>
inline constexpr T get_max_v = std::numeric_limits<T>::max();

template <typename T, typename U>
std::enable_if_t<get_max_v<T> == get_max_v<U>, bool>
same_max() {
return true;
}

template <typename T, typename U>
std::enable_if_t<get_max_v<T> != get_max_v<U>, bool>
same_max() {
return false;
}

为了避免某些 header (例如 windef.h)中定义的 min/max 宏出现潜在问题,可以将函数名称放在括号中:

... = (std::numeric_limits<T>::max)();

关于c++ - MSVC2017 上的 SFINAE 与 numeric_limits<T>::max(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59743372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com