Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize a Struct containing a const array with initializer list

I working with C++11 and have a Class containing the following Struct:

struct Settings{
    const std::string name;

    const std::string* A;
    const size_t a;
};

class X {
    static const Settings s;
    //More stuff
};

In the .cpp file I want to define it like this

X::s = {"MyName", {"one","two","three"}, 3};

But this does not work. However it does work using an intermediate variable

const std::string inter[] = {"one","two","three"};
X::s = {"MyName", inter, 3};

Is there a way to do it without the intermediate variable?

like image 942
Haatschii Avatar asked May 21 '13 18:05

Haatschii


1 Answers

A pointer cannot be initialized from a list of values. You could use std::vector instead:

#include <vector>

struct Settings{
    const std::string name;
    const std::vector<std::string> A;
//        ^^^^^^^^^^^^^^^^^^^^^^^^
    const size_t a;
};

You can then write:

class X {
    static const Settings s;
    //More stuff
};

const Settings X::s = {"MyName", {"one","two","three"}, 3};

Here is a live example.

As suggested by Praetorian in the comments, you may want to replace std::vector with std::array, if it is acceptable for you to specify the size of the container explicitly, and if the size does not need to change at run-time:

#include <array>

struct Settings{
    const std::string name;
    const std::array<std::string, 3> A;
//        ^^^^^^^^^^^^^^^^^^^^^^^^^^
    const size_t a;
};

And here is the live example.

like image 131
Andy Prowl Avatar answered Oct 06 '22 01:10

Andy Prowl