Initializing static constexpr variables and classes inside a struct

不问归期 提交于 2019-11-29 09:34:48

A static constexpr member has a value upon its initialization inside the class { } scope, but it does not have a location in memory (an address) until it is defined outside the class { }. The reason is that you may decide to include some or all of its specializations in a link library (e.g. .o or .so), or whether to give effectively-inline linkage to specializations by default.

The out-of-class definition is required if the address of the object is ever used, which implies that it must exist as a global variable. On the other hand, if you want the constexpr member only to exist at compile time, prohibiting global storage allocation, then omitting the definition is a good choice.

By the way, it's not allowed to put the constexpr specifier on a function that can never be evaluated as a constant expression, such as sayhi which prints to std::cout. This is a "no diagnostic required (NDR)" rule, meaning that the compiler might not complain now but the next compiler version might.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!