尝试实现 is_constexpr() - 编译器出现分歧

Attempt to implement is_constexpr() - compilers diverge

以下是基于Richard Smith's answer to Is is_constexpr possible in C++11?

实现is_constexpr()的三种尝试

版本 1

template <typename T>
bool constexpr is_constexpr_impl_1(const T& x, decltype(int{(x, 0u)})) { return true; }

template <typename T>
bool constexpr is_constexpr_impl_1(const T&, ...) { return false; }

template <typename T>
bool constexpr is_constexpr_1(const T& x) { return is_constexpr_impl_1(x, 0); }

版本 2

template <typename T>
bool constexpr is_constexpr_impl_2(const T& f, decltype(int{(f(0), 0u)})) { return true; }

template <typename T>
bool constexpr is_constexpr_impl_2(const T&, ...) { return false; }

template <typename T>
bool constexpr is_constexpr_2(const T& f) { return is_constexpr_impl_2(f, 0); }

版本 3

template <auto f>
bool constexpr is_constexpr_impl_3(decltype(int{(f(0), 0u)})) { return true; }

template <auto f>
bool constexpr is_constexpr_impl_3(...) { return false; }

template <auto f>
bool constexpr is_constexpr_3() { return is_constexpr_impl_3<f>(0); }

我已经使用 gcc 9.1、clang 8.0.0、icc 19.0.1 和 msvc 19.20 以及以下函数的帮助测试了上述内容(参见 godbolt):

void constexpr f_c(int) {}
void f_nc(int) {}
下面的

Table 显示了我在 static_assert 中输入的表达式。我希望所有这些都通过,但编译器不同意我和他们之间的意见(除了 icc 和 msvc 彼此同意):

                        | gcc  | clang | icc  | msvc |
 is_constexpr_1(0)      | pass | fail  | pass | pass |
 is_constexpr_2(f_c)    | fail | fail  | pass | pass |
!is_constexpr_2(f_nc)   | pass | pass  | fail | fail |
 is_constexpr_3<f_c>()  | pass | pass  | pass | pass |
!is_constexpr_3<f_nc>() | pass | pass  | fail | fail |

谁是对的,为什么? (标准中的引述会很有用。)

is_constexpr_1is_constexpr_2 都无效,因为它们 运行 违反了常量表达式中不能使用函数参数的通常规则。它们分别要求 xf 至少有时可用作常量表达式,但它们永远不会。

在这种情况下,[expr.const]/4 限制:

an id-expression that refers to a variable or data member of reference type unless the reference has a preceding initialization and either [...]

其他两个项目符号是什么无关紧要,因为我们没有对引用变量的 id-expression 进行预先初始化。

is_constexpr_3 是有效的,正如 Richard Smith 在 linked answer.

中解释的那样

我的期望是:

                        | 
 is_constexpr_1(0)      | fail
 is_constexpr_2(f_c)    | fail
!is_constexpr_2(f_nc)   | pass
 is_constexpr_3<f_c>()  | pass
!is_constexpr_3<f_nc>() | pass

这就是 clang 的作用。