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

Viewed 889

I need a const object of std::set, which will be used in many other cpp files. Since that the initializing-order of each parts of the app is undefined, I may get a empty set when I initialize other const objects with this std::set obj.

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 get it? or not at all?

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 };
Related