如果我的类是文字类,那么将我的类的对象声明为constexpr是否多余?

Mae*_*tro 14 c++ oop constexpr

我有一个constexpr类Debug:

struct Debug {
  constexpr Debug(bool a, bool b, bool c) : a(a), b(b), c(c) {}
  bool a, b, c;
  constexpr bool get() const { return a; }
};

int main() {
  Debug dbg(true, false, false); // is dbg constexpr object?
  constexpr Debug dbg2(0, 0, 0); // is constexpr redundant here?
}
Run Code Online (Sandbox Code Playgroud)

如您所见,这dbg是一个constexpr对象,因为它是用constexpr构造函数初始化的,所以如果我用constexpr对其进行限定,那有什么意义呢?

  • 我不知道之间的区别dbgdbg2。谢谢。

Vit*_*meo 11

主要区别在于:仅dbg2可用于需要常量表达式的地方。例如,考虑即将推出的C ++ 20功能,该功能允许使用任意非类型模板参数:

template <Debug> void f() { }
Run Code Online (Sandbox Code Playgroud)

具有以上定义,f<dgb2>()将编译,而f<dgb>()不会。

f<dgb>();
Run Code Online (Sandbox Code Playgroud)
<source>:7:29: note:   template argument deduction/substitution failed:

<source>:13:12: error: the value of 'dbg' is not usable in a constant expression
   13 |   foo<dbg>();  // ERROR
      |            ^

<source>:10:9: note: 'dbg' was not declared 'constexpr'
   10 |   Debug dbg(true, false, false); // is dbg constexpr object?
Run Code Online (Sandbox Code Playgroud)

Godbolt.org上的实时示例


这在C ++ 11中也很重要。您将能够说:

template <bool> void g() { }
g<dgb2.a>();
Run Code Online (Sandbox Code Playgroud)

但不是:

g<dgb.a>();
Run Code Online (Sandbox Code Playgroud)

Godbolt.org上的实时示例