Convenient C++ struct initialisation

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

    Your question is somewhat difficult because even the function:

    static FooBar MakeFooBar(int foo, float bar);
    

    may be called as:

    FooBar fb = MakeFooBar(3.4, 5);
    

    because of the promotion and conversions rules for built-in numeric types. (C has never been really strongly typed)

    In C++, what you want is achievable, though with the help of templates and static assertions:

    template 
    FooBar MakeFooBar(Integer foo, Real bar) {
      static_assert(std::is_same::value, "foo should be of type int");
      static_assert(std::is_same::value, "bar should be of type float");
      return { foo, bar };
    }
    

    In C, you may name the parameters, but you'll never get further.

    On the other hand, if all you want is named parameters, then you write a lot of cumbersome code:

    struct FooBarMaker {
      FooBarMaker(int f): _f(f) {}
      FooBar Bar(float b) const { return FooBar(_f, b); }
      int _f;
    };
    
    static FooBarMaker Foo(int f) { return FooBarMaker(f); }
    
    // Usage
    FooBar fb = Foo(5).Bar(3.4);
    

    And you can pepper in type promotion protection if you like.

提交回复
热议问题