Convenient C++ struct initialisation

后端 未结 13 743
谎友^
谎友^ 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:43

    For versions of C++ prior to C++20 (which introduces the named initialization, making your option A valid in C++), consider the following:

    int main()
    {
        struct TFoo { int val; };
        struct TBar { float val; };
    
        struct FooBar {
            TFoo foo;
            TBar bar;
        };
    
        FooBar mystruct = { TFoo{12}, TBar{3.4} };
    
        std::cout << "foo = " << mystruct.foo.val << " bar = " << mystruct.bar.val << std::endl;
    
    }
    

    Note that if you try to initialize the struct with FooBar mystruct = { TFoo{12}, TFoo{3.4} }; you will get a compilation error.

    The downside is that you have to create one additional struct for each variable inside your main struct, and also you have to use the inner value with mystruct.foo.val. But on the other hand, it`s clean, simple, pure and standard.

提交回复
热议问题