Home > database >  Is there a way to make a struct take a variadic list of elements in a nested struct to be constexpr
Is there a way to make a struct take a variadic list of elements in a nested struct to be constexpr

Time:11-11

Say I have this struct layout:

#include <vector>
struct A {
    char const* name;
    std::vector<char const*> list;
};

struct B {
    char const* group_name;
    A an_A;
    int other_stuff;
};

Which I initialize thusly:

B b = {
 "My B",
  { "My A",
    {{ "My", "variable", "length", "list" }}
  },
  42
};

Is there any way to define this so that b can be constexpr without having to resort to declarations of subitems before the main item?

Thought this might work using a initializer_list:

#include  <initializer_list>

struct A {
    char const* name;
    std::initializer_list<char const*> list;
};

struct B {
    char const* group_name;
    A an_A;
    int other_stuff;
};

B b = {
 "My B",
  { "My A",
    {{ "My", "variable", "length", "list" }}
  },
  42
};

But alas I get the following errors:

<source>:20:1: error: could not convert '{{"My", "variable", "length", "list"}}' from '<brace-enclosed initializer list>' to 'std::initializer_list<const char*>'
   20 | };
      | ^
      | |
      | <brace-enclosed initializer list>
ASM generation compiler returned: 1
<source>:20:1: error: could not convert '{{"My", "variable", "length", "list"}}' from '<brace-enclosed initializer list>' to 'std::initializer_list<const char*>'
   20 | };
      | ^
      | |
      | <brace-enclosed initializer list>
Execution build compiler returned: 1

Demo

CodePudding user response:

The problem is that you've specified extra braces around { "My", "variable", "length", "list" } in your second example.

Thus to solve this you need to remove those extra braces {} as shown below:

B b = {
 "My B",
  { "My A",
//-v--------------------------------------v---->removed extra braces from here
    { "My", "variable", "length", "list" }
  },
  42
};

Working demo

  • Related