c++ - 默认情况下,静态变量是否在 C++17 的模板中内联?

标签 c++ templates inline c++17

在 C++17 的模板中是否默认内联静态变量?这是一个例子:

template<typename T>
struct SomeClass {
    static T test;
};

struct SomeClass2 {
    static constexpr int test = 9;
};

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

最佳答案

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

template<typename T>
struct SomeClass {
    inline static T test; // Now inline
};

struct SomeClass2 {
    static constexpr int test = 9; // inline
};

参照。来自 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)

[dcl.constexpr](巴里打败了我)

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

关于c++ - 默认情况下,静态变量是否在 C++17 的模板中内联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40658617/

相关文章:

c++ - 编译器会优化模板 bool 吗?

c++ - 如何根据编译时参数使用内联函数的不同重载?

html - 如何在 Wordpress 中内联编辑 HTML、CSS 代码

html - 如何使用 html/css 显示内联和居中的多个图像?

c++ - 设置 GtkLinkBut​​tons 的样式

c++ - 错误 : expected unqualified-id before string constant

c++ - 在函数中添加参数时重建动态库

C++ 模板,模棱两可的重载

c++ - 如何typedef未参数化模板?

c++ - C++创建线程进程