Convenient C++ struct initialisation

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

    You could use a lambda:

    const FooBar fb = [&] {
        FooBar fb;
        fb.foo = 12;
        fb.bar = 3.4;
        return fb;
    }();
    

    More information on this idiom can be found on Herb Sutter's blog.

提交回复
热议问题