Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need a const object of type std::set, which will be used in many other cpp files. Since the initialization order of each translation unit is undefined, I may get an empty set when I initialize other const objects with this std::set object.

So, I want make this std::set as constexpr, but it can not be compiled. I want to have:

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

Is there a way to do this, or none at all?

like image 845
Leon Avatar asked Sep 16 '25 07:09

Leon


2 Answers

You cannot use constexpr here since std::set has no constexpr constructors.

What you can do though is declare the variable as an inline const variable and that will allow you to include it in every translation unit and provide an initializer. That would look like

//header file
inline const std::set<int> EARLIER_SET = { 1, 2, 3 };
like image 117
NathanOliver Avatar answered Sep 17 '25 21:09

NathanOliver


Not at all in the standard library.

But you might be interested in: https://github.com/serge-sans-paille/frozen

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

would then be valid.

like image 30
One Lyner Avatar answered Sep 17 '25 21:09

One Lyner