Are static variables inlined by default inside templates in C++17? Here's an example:
template<typename T> struct SomeClass { static T test; }; struct SomeClass2 { static constexpr int test = 9; };
Are those variables inlined or still need an out of line definition to be ODR used?
Global and static variables are initialized to their default values because it is in the C or C++ standards and it is free to assign a value by zero at compile time. Both static and global variable behave same to the generated object code.
A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.
A variable declared inline has the same semantics as a function declared inline: it can be defined, identically, in multiple translation units, must be defined in every translation unit in which it is used, and the behavior of the program is as if there was exactly one variable.
A static constexpr
will implicitly also be inline
, otherwise you will need to mark it as inline
template<typename T> struct SomeClass { inline static T test; // Now inline }; struct SomeClass2 { static constexpr int test = 9; // inline };
Cfr. from n4606 [depr.static_constexpr]
For compatibility with prior C++ International Standards, a constexpr static data member may be redundantly redeclared outside the class with no initializer. This usage is deprecated.
Example:
struct A { static constexpr int n = 5; // definition (declaration in C++ 2014) }; const int A::n; // redundant declaration (definition in C++ 2014)
and [dcl.constexpr]
(Barry beat me to it)
A function or static data member declared with the constexpr specifier is implicitly an inline function or variable (7.1.6).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With