我正在使用可变宽度通信格式。处理它的结构看起来像这样:
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
member 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
必须在声明中写明。定义应该放在same标头以避免任何翻译单元看到声明但看不到inline
,这是不允许的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)