简体   繁体   English

使用内联 static 成员而不是 static 成员

[英]Using inline static member instead of static member

I have a following struct:我有以下结构:

#include <iostream>

struct Foo
{
  static int a;               // declaration
  inline static int b = 10;   // declaration and definition
};

int Foo::a = 10; // definition

int main()
{
  std::cout << Foo::a << "\n"; // --> 10
  std::cout << Foo::b << "\n"; // --> 10 (same result as Foo::b)

  return 0;
}

It is "easier" to use inline static to achieve same goal as when static is used.使用inline static实现与使用static时相同的目标“更容易”。

Is there any case when using static members for class instead of inline static members is more preferable/required?在任何情况下,使用static成员作为 class 而不是inline static成员更可取/需要?

Note: there is an obvious case when one uses C++14 or lower standard.注意:当使用 C++14 或更低标准时,有一个明显的情况。

You'd see it if you ever try to create "stateful enums".如果您尝试创建“有状态枚举”,就会看到它。 Basically, classes that capture a little data and there is a handful of "named constants" of that type that you'd want to codify as static data members.基本上,捕获少量数据的类以及您想要将其编码为 static 数据成员的少量该类型的“命名常量”。 To illustrate:为了显示:

struct RGB {
    inline static RGB c1{1};
    inline static RGB c2{2};
    RGB(int, int = 0, int = 0);
};

This will be ill-formed, whereas this will not:这将是错误的,而这不会:

struct RGB {
    static RGB c1;
    static RGB c2;
    RGB(int, int = 0, int = 0);
};

RGB RGB::c1{1};
RGB RGB::c2{2};

Live example 实例

The reason is that a static data member may have an incomplete type, but it must be complete when initialised.原因是 static 数据成员的类型可能不完整,但在初始化时必须是完整的。

It will naturally pop up when playing with constexpr static members.玩constexpr static成员的时候自然会弹出。 Come C++17, they are implicitly inline, so you'd have to break the declaration from definition if you want to have them:来吧 C++17,它们是隐式内联的,所以如果你想拥有它们,你必须从定义中打破声明:

struct RGB {
    static const RGB c1;
    static const RGB c2;
    constexpr RGB(int, int = 0, int = 0){}
};

constexpr RGB RGB::c1{1};
constexpr RGB RGB::c2{2};

Live example 实例

Those are valid constant, and are usable in constant expressions.这些是有效常量,可用于常量表达式。 But they cannot be defined inline as static data members.但它们不能内联定义为 static 数据成员。 They are still technically inline data members on account of being constexpr , but are not defined inline (mind though that it's true prior to C++17 too, but the constant cannot be defined in a header for redefinition errors, so they are essentially unusable).由于是constexpr ,它们在技术上仍然是内联数据成员,但未定义为内联(请注意,它在 C++17 之前也是如此,但常量不能在 header 中定义以重新定义错误,因此它们基本上不可用)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM