Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to make a struct take a variadic list of elements in a nested struct to be constexpr without initializing it in multiple parts?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading