简体   繁体   中英

need many parameters on construction c++03

I have an object that looks somewhat like

class Block{
     Type1 member1;
     Type2 member2;
     Type3 member3;
     ...
     //many many MANY members (hundreds, if not thousands)
}

I need to create a convenient way to construct Block.

This calls for the builder pattern, but as shown here https://en.wikipedia.org/wiki/Builder_pattern it seems I would exceed the maximum number of parameters allowed on the constructor.

How should I do this? Separation to smaller blocks is an option i would rather avoid.

Thanks

There should be design issue here, I don't think you really used the hundreds members. class should be designed the simple the better. You should provide more details for this class.

I don't think you are groking the builder pattern. Define a configuration object. Define individual methods to set the configuration object. Then use the configuration object to instantiate object.

class BlockCfg {
    //...
    void setMember1 (Type1 val);
    void setMember2 (Type2 val);
    //...
};

class Block {
    Block (const BlockCfg &cfg);
};

You could make BlockBuilder a friend of Block , then have the BlockBuilder functions directly modify the member data rather than passing in all the data to the constructor. The downside of this is that all the members of Block will be default-constructed, which might be fine if most of the types are built-in, but might be expensive.

However, having hundreds of members in a class is a massive code smell and you should think about a redesign.

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