Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static constexpr of set

Tags:

c++

c++11

enum class PARAM_TYPE_ {INT_};
enum class PARAM_NAME_ {NAME_};
typedef std::pair<PARAM_NAME_,PARAM_TYPE_> PARAM_;

static constexpr std::unordered_set<PARAM_> params_ {
        PARAM_(PARAM_NAME_::NAME_,PARAM_TYPE_::STRING_)
};

Why is it not possible to put this in my classes header file?

I tried for a long time to figure out why it is not possible to use the combination of:

static, constexpr, non-literal type

But my overall c++ knowledge is just too limited.

like image 664
Felix Crazzolara Avatar asked Jun 11 '26 00:06

Felix Crazzolara


1 Answers

From constexpr:

A constexpr variable must satisfy the following requirements:

  • its type must be a literal type
  • it must be immediately initialized
  • the full-expression of its initialization, including all implicit conversions, constructors calls, etc, must be a constant expression

Now, from literal type we can conclude that a literal type might be an an aggregate type, a type with at least one constexpr (possibly template) constructor that is not a copy or move constructor or, since C++17, a closure type.

From std::unordered_set we see that there are no constexpr constructors. Other two cases are not applicable as well, so you cannot mark std::unordered_set as constexpr.

Basically, you use std::unordered_set with a default allocator which implies dynamic memory allocation. Dynamic memory allocation is a runtime thing when constexpr is a totally compile time beast.

like image 63
Edgar Rokjān Avatar answered Jun 13 '26 01:06

Edgar Rokjān



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!