Convenient C++ struct initialisation

后端 未结 13 769
谎友^
谎友^ 2020-12-07 10:15

I\'m trying to find a convenient way to initialise \'pod\' C++ structs. Now, consider the following struct:

struct FooBar {
  int foo;
  float bar;
};
// jus         


        
13条回答
  •  清歌不尽
    2020-12-07 10:42

    For me the laziest way to allow inline inizialization is use this macro.

    #define METHOD_MEMBER(TYPE, NAME, CLASS) \
    CLASS &set_ ## NAME(const TYPE &_val) { NAME = _val; return *this; } \
    TYPE NAME;
    
    struct foo {
        METHOD_MEMBER(string, attr1, foo)
        METHOD_MEMBER(int, attr2, foo)
        METHOD_MEMBER(double, attr3, foo)
    };
    
    // inline usage
    foo test = foo().set_attr1("hi").set_attr2(22).set_attr3(3.14);
    

    That macro create attribute and self reference method.

提交回复
热议问题