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?

2 Answers 2

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.