Kabu
Kabu

Reputation: 569

How do I initialize this struct?

Sorry for being not specific, but...

Suppose I have this struct:

struct OptionData
{
    Desc desc;
    bool boolValue;
    std::string stringValue;
    int intValue;
    double numberValue;
};

which I'm using this way:

OptionData isWritePatchesOptionData = {isWritePatchesDesc, {}, {}, {}, {}};

As I have lots of those options, I'd like to do s.t. like this:

<type_here> OptionDataList = {{}, {}, {}, {}};

so I can do:

OptionData isSeamCutOptionData = {isSeamCutDesc, OptionDataList};

but really on the spot I can't figure what type_here would be... Or maybe is not possible in this form... I mean, without creating an OptionDataList object into the OptionData struct... but that clearly would be redundant...

Upvotes: 1

Views: 69

Answers (1)

NathanOliver
NathanOliver

Reputation: 180594

Just provide default initializers. Using

struct OptionData
{
    Desc desc{};
    bool boolValue{};
    std::string stringValue{};
    int intValue{};
    double numberValue{};
};

Everything in the struct will be value initialized meaning objects with a constructor will be default constructed and objects without a constructor will be zero initialized.

This lets you write

OptionData isWritePatchesOptionData = {isWritePatchesDesc}; // same as using {isWritePatchesDesc, {}, {}, {}, {}};
// and
OptionData isSeamCutOptionData = {isSeamCutDesc};

and now all of the other members are in a default/zero state.

Upvotes: 2

Related Questions