Guillaume Racicot Guillaume Racicot - 23 days ago 6
C++ Question

Is C++17 inline variable is applied by default in templates?

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 constepxr int test = 9;
};


Are those variables inlined or still need an out of line definition to be ODR used?

Answer

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