我如何才能检测到构造器确实是constexpr,因此可以利用静态初始化? [英] How can I detect that a constuctor is really constexpr, so I can utilize static initialization?
问题描述
看下面的代码:
struct NonConstexpr {
NonConstexpr() { }
};
template <typename T>
struct Bar {
NonConstexpr nonConstexpr;
constexpr Bar() { }
};
struct Foo {
Bar<void> bar;
constexpr Foo() { }
};
在此代码中, Foo
的构造函数标记为 constexpr
,但它不能出现在常量表达式中,因为它实际上不能满足此要求。您可以在我的上一个问题中阅读详细信息。
In this code, Foo
's constructor is tagged as constexpr
, but it cannot appear in a constant expression, as it actually fails to satisfy the requirements of this. You can read the details of this in my previous question.
我的问题是:我能以某种方式检测编译时间,即 Foo
的构造函数不会表现为 constexpr
?
My question is: can I detect somehow compile-time, that Foo
's constructor actually won't behave as constexpr
?
我问这个原因的原因是,我想发现一个全局变量 Foo
的变量是否将被静态初始化(我想在此变量上放置 static_assert
,因为 Foo
对象必须静态初始化)。
The reason I ask this, I'd like to detect that a global variable of Foo
will be statically initialized or not (I'd like to put a static_assert
on this, as my global Foo
object must be initialized statically).
请注意,简单的解决方案是临时添加 constexpr
对该变量不起作用,因为我的 Foo
具有非平凡的析构函数。
Note, that the straightforward solution, to temporarily add constexpr
to the variable doesn't work, as my Foo
has a non-trivial destructor.
推荐答案
如果使用的是Clang,请在变量上使用 [[clang :: require_constant_initialization]]
。否则,我不知道有什么办法。
If you are using Clang, use [[clang::require_constant_initialization]]
on the variable. Otherwise, I don't know of a way.
委员会正在考虑将其标准化为关键字。
The committee is looking at standardizing this as a keyword.
这篇关于我如何才能检测到构造器确实是constexpr,因此可以利用静态初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!