我可以创建 std::set 的 constexpr 对象吗?

Can I make a constexpr object of std::set?

我需要一个std::set的const对象,在其他很多cpp文件中都会用到。 由于应用程序每个部分的初始化顺序未定义,因此当我使用此 std::set obj.

初始化其他 const 对象时,我可能会得到一个空集

所以,我想把这个 std::set 作为 constexpr,但它无法编译。 我想要:

constexpr std::set<int> EARLIER_SET = { 1, 2, 3 };

有办法得到吗?或者根本没有?

标准库中根本没有。

但您可能对以下内容感兴趣:https://github.com/serge-sans-paille/frozen

constexpr frozen::set<int, 3> EARLIER_SET = { 1, 2, 3 };

然后才有效。

您不能在此处使用 constexpr,因为 std::set 没有 constexpr 构造函数。

您可以做的是将变量声明为 inline const 变量,这样您就可以将它包含在每个翻译单元中并提供初始化程序。看起来像

//header file
inline const std::set<int> EARLIER_SET = { 1, 2, 3 };