我惊讶地发现,当没有类外定义时,GCC 和 Clang 在按值传递静态 constexpr 成员时是否给我一个链接器错误意见不一:
#include <iostream>
#include <type_traits>
#include <typeinfo>
template <typename X>
void show(X)
{
std::cout << typeid(X).name() << std::endl;
}
template <typename T>
struct Foo
{
//static constexpr struct E {} nested {}; // works in gcc and clang
//static constexpr struct E {T x;} nested {}; // doesn't work in gcc
//static constexpr enum E {} nested {}; // works in gcc and clang
//static constexpr enum E { FOO } nested {}; // works in gcc and clang
//static constexpr struct E { constexpr E() {} constexpr E(const E&) {} T x=T();} nested {}; // works in gcc and clang
static constexpr struct E { constexpr E() {} constexpr E(const E&) = default; T x=T(); } nested {}; // doesn't work in gcc
};
int main()
{
Foo<int> x;
show(x.nested);
}
片段可以在这里播放。
我想使用没有类外定义的第一行语法:
static constexpr struct E {} nested {}; // works in gcc and clang
当 中没有成员时E
,Clang 和 GCC 似乎只关心我是否对nested
ODR 跳闸没有课外定义(例如,通过获取地址)。这个标准是强制性的还是运气?
当有成员时,GCC(5.2)似乎还希望我手动定义一个 constexpr 复制构造函数。这是一个错误吗?
从谷歌搜索和 SO 我发现了几个不同的答案,但很难区分哪些是最新的 C++14。在 C++98/03 中,我相信只能在类中初始化整数类型。我认为C++14 将其扩展为“文字”类型,其中包括 constexpr 可构造的东西。我不知道这是否与说我可以在没有课外定义的情况下逍遥法外是一样的。