22

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?

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141

2 Answers2

22

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

Uyghur Lives Matter
  • 18,820
  • 42
  • 108
  • 144
Marco A.
  • 43,032
  • 26
  • 132
  • 246
12

From [dcl.constexpr]:

A function or static data member declared with the constexpr specifier is implicitly an inline function or variable (7.1.6).

There is no such implicit inline for static (non-constexpr) data members of class templates. However, in C++17, we can now mark variables themselves as inline, [dcl.inline]:

A variable declaration with an inline specifier declares an inline variable.

Barry
  • 286,269
  • 29
  • 621
  • 977