当类具有 constexpr 成员函数并且正在 constexpr 上下文中对左值对象求值时,clang 和 gcc 不同意结果是否为 constexpr 值。
为什么?是否有一种既不需要默认可构造性也不需要复制可构造性的解决方法?
当对象按值传递时,两个编译器都会成功编译。
Clang 版本主干、8、7:static_assert expression is not an integral constant expression
and
Gcc 版本 trunk、8.1、7.4:编译没有错误
#include <array>
using A = std::array<int, 10>;
void foo(const A& a){
// clang: static_assert expression is not an integral constant expression
static_assert(a.size() > 0, "");
}
void foo2(A a){
// this compiles on both clang and gcc
static_assert(a.size() > 0, "");
}
// Some custom code with the same symptom:
class B{
public:
constexpr int size()const{
return 42;
}
};
void foo3(const B& b){
// clang: static_assert expression is not an integral constant expression
static_assert(b.size() > 0, "");
}
void foo4(B b){
// this compiles on both clang and gcc
static_assert(b.size() > 0, "");
}
https://godbolt.org/z/9vmyli https://godbolt.org/z/9vmyli
带有警告的解决方法:
void foo5(const B& b){
// This works in clang, if the default constructor is defined
static_assert(B().size() > 0, "");
}
void foo6(const B& b){
// This works in clang, if the copy constructor is defined
[](B b){static_assert(b.size() > 0, "");}(b);
}