在c++ 17中,静态变量是否默认内联在模板中

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

本文关键字:默认 变量 c++ 静态 是否      更新时间:2023-10-16

静态变量是否默认内联在c++ 17模板内?下面是一个例子:

template<typename T>
struct SomeClass {
    static T test;
};
struct SomeClass2 {
    static constexpr int test = 9;
};

这些变量是内联的还是仍然需要行外定义才能使用ODR ?

A static constexpr将隐式地也为inline,否则您需要将其标记为inline

template<typename T>
struct SomeClass {
    inline static T test; // Now inline
};
struct SomeClass2 {
    static constexpr int test = 9; // inline
};

病死率。from n4606 [depr.static_constexpr]

为了与先前的c++国际标准兼容,constexpr静态数据成员可以在没有初始化项的情况下在类外部冗余地重新声明。

的例子:

struct A {
  static constexpr int n = 5; // definition (declaration in C++ 2014)
};
const int A::n; // redundant declaration (definition in C++ 2014)

[dcl.constexpr] (Barry先我一步)

用constexpr说明符声明的函数或静态数据成员隐式地是内联函数或变量(7.1.6)。

From [dcl.constexpr]:

constexpr声明的函数或静态数据成员说明符是隐式内联函数或变量(7.1.6)。

对于类模板的静态(非constexpr)数据成员,没有这样的隐式inline。然而,在c++ 17中,我们现在可以将变量本身标记为inline, [dcl.inline]:

带有inline说明符的变量声明声明了一个内联变量。