Initialize array in constructor without using default constructor or assignment

后端 未结 4 405
日久生厌
日久生厌 2021-01-13 03:56

Consider:

struct A {

 A (int);

 A (const A &);
};

struct B {

 A foo [2];

 B (const A & x, const A & y)
 : foo {x, y} /* HERE IS THE PROBLEM          


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-13 04:15

    You can use boost::array. It has a plain native array inside, so it still has the same memory layout like in your example.

    struct B {
     boost::array foo;
    
     B (const A & x, const A & y)
     : foo(createFoo(x, y))
     {}
    
    private:
     static boost::array createFoo(const A & x, const A & y) {
       boost::array a = {{ x, y }};
       return a;
     }
    };
    

    If you don't have boost you can create your own array class or use std::tr1 if your compiler has it

    template
    struct array {
      T data[N];
    };
    

    That's all you need, but you can add the usual begin, end, size functions and so on to make it more comfortable to use.

提交回复
热议问题