Convenient C++ struct initialisation

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

    Extract the contants into functions that describe them (basic refactoring):

    FooBar fb = { foo(), bar() };
    

    I know that style is very close to the one you didn't want to use, but it enables easier replacement of the constant values and also explain them (thus not needing to edit comments), if they ever change that is.

    Another thing you could do (since you are lazy) is to make the constructor inline, so you don't have to type as much (removing "Foobar::" and time spent switching between h and cpp file):

    struct FooBar {
      FooBar(int f, float b) : foo(f), bar(b) {}
      int foo;
      float bar;
    };
    

提交回复
热议问题