首页 > 解决方案 > 为什么 SFINAE 没有给出递增布尔值的正确结果?

问题描述

我写了一个is_incrementable这样的特征:

#include <type_traits>

template <typename T, typename = void>
struct is_incrementable : std::false_type {};

template <typename T>
struct is_incrementable<T, std::void_t<decltype(++std::declval<T&>())>>
    : std::true_type {};

template <typename T>
constexpr bool is_incrementable_v = is_incrementable<T>::value;

当我将它应用到boolwith -std=c++17on clang 时,它返回true

// This compiles
static_assert(is_incrementable_v<bool>, "");

bool但在 c++17 下不允许递增。事实上,如果我尝试这样做,我会收到一个错误:

bool b = false;
++b;

结果是:

error: ISO C++17 does not allow incrementing expression of type bool [-Wincrement-bool]

bool当编译器明确不允许时,为什么 SFINAE 报告它是可递增的?

编译器资源管理器:https ://godbolt.org/g/DDFYBf

标签: c++sfinaetypetraits

解决方案


看起来 Clang 错误地允许bool在未评估的上下文中增加值。

我们可以使用 C++20 概念简化您的示例:

template<class T>
concept is_incrementable = requires(T t) {
    { ++t };
};

int main() {
    static_assert( is_incrementable<int> );
    static_assert( !is_incrementable<bool> ); // Clang error here
}

该程序在 GCC 和 MSVC 中被接受,但 Clang 在这里显示相同的错误行为,演示:https ://gcc.godbolt.org/z/YEnKfG8T5

我认为是 Clang 的 bug,所以提交了一个 bug 报告:https ://bugs.llvm.org/show_bug.cgi?id=52280


推荐阅读