我可以制作一个 std::set 类型的 constexpr 对象吗?

问题描述 投票:0回答:2

我需要一个

std::set
类型的const对象,它将在许多其他cpp文件中使用。 由于每个翻译单元的初始化顺序是未定义的,当我用这个
std::set
对象初始化其他 const 对象时,我可能会得到一个空集。

所以,我想把这个

std::set
变成
constexpr
,但是无法编译。 我想要:

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

有办法做到这一点,还是根本没有办法?

c++ std constexpr stdset initialization-order
2个回答
4
投票

此处不能使用

constexpr
,因为
std::set
没有
constexpr
构造函数。

您可以做的是将变量声明为

inline const
变量,这将允许您将其包含在每个翻译单元中并提供初始值设定项。那看起来像

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

4
投票

标准库中根本没有。

但您可能感兴趣:https://github.com/serge-sans-paille/frozen

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

那么就有效了。

© www.soinside.com 2019 - 2024. All rights reserved.