Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static variables inlined by default inside templates in C++17?

Tags:

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?

like image 824
Guillaume Racicot Avatar asked Nov 17 '16 15:11

Guillaume Racicot


People also ask

Are C variables static by default?

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.

Is Constexpr variable inline?

A static member variable (but not a namespace-scope variable) declared constexpr is implicitly an inline variable.

Can a variable be inline?

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.


1 Answers

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).

like image 110
Marco A. Avatar answered Sep 29 '22 11:09

Marco A.