我可以在类外初始化一个`constexprstatic`成员吗?
我正在使用可变宽度的通信格式。处理它的结构看起来像这样:
struct Header
{
int msgType = -1, len;
Header() { len = sizeof(*this); }
};
struct A : public Header
{
int x; char y;
A() { msgType = 1; len = sizeof(*this); }
};
// Further structs B, C, ... declared along the same lines
我想要一个constexpr static成员Header::MAX_SIZE,它给出任何这些派生类的最大大小,例如,这样我就可以分配一个缓冲区,保证可以容纳任何此类数据包。所以我想做类似的事情
struct Header
{
int msgType = -1, len;
constexpr static std::size_t MAX_SIZE;
Header() { len = sizeof(*this); }
};
// ... declaration of subclasses ...
inline Header::MAX_SIZE = std::max({ sizeof(A), sizeof(B), sizeof(C) });
我需要定义在类之外,因为它依赖于sizeof(A)等,而这些又依赖于Header.
看起来这种事情应该是无可争议的:我在同一个源文件中给出了成员的定义,并且可以在编译时计算。但是我还没有找到任何方法来告诉编译器实际执行此操作。
回答
constexpr继续一个变量的初始化声明,所以把它放在类之外:
struct Header
{
int msgType = -1, len;
static const std::size_t MAX_SIZE;
Header() { len = sizeof(*this); }
};
// ... declaration of subclasses ...
inline constexpr std::size_t Header::MAX_SIZE = std::max({ sizeof(A), sizeof(B), sizeof(C) });
请注意,隐式const必须在声明中详细说明。定义应该放在同一个标题中,以避免任何翻译单元看到声明而不是inline,这是不允许的。