简体   繁体   中英

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 st 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...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM