Home > Software engineering >  type for aliasing constexpr char[]
type for aliasing constexpr char[]

Time:10-13

In the given code base, there are tons of constexpr char[] variables. I'd like to alias them.

constexpr char FieldX[] = "my_field_or_option";
// using OptY = FieldX???

I've tried a few different things but neither actually worked. In the example above, I'd like to have OptY as effectively constexpr char[]. The value won't change at runtime but someone could change the value of FieldX later on and re-compile. I do not want to change OptY accordingly and manually.

What'd be the data type for OptY so that I could do this?

Type OptY = FieldX;

CodePudding user response:

If you want an alias of a variable, you want a reference.

constexpr char FieldX[] = "my_field_or_option";
constexpr auto& OptY = FieldX;

static_assert( sizeof FieldX == 19 );
static_assert( sizeof OptY == 19 );    // No array decay

Note that FieldX must be evaluated at compile time to be able to create a constexpr reference to it, meaning it should be global or static.

Demo

CodePudding user response:

I'd like to have OptY as effectively constexpr char[]

With modern C , you could use decltype as shown below:

constexpr char FieldX[] = "my_field_or_option";
using OptY = decltype(FieldX);     //create an alias
static_assert(sizeof(OptY) == 19);

Demo

  • Related