Why did C++11 introduce delegating constructors?

前端 未结 5 992
小鲜肉
小鲜肉 2020-12-24 08:34

I cannot understand what the use is of delegating constructors. Simply, what cannot be achieve without having delegating constructors?

It can do something simple li

5条回答
  •  一生所求
    2020-12-24 09:07

    One key use of delegating constructors that doesn't merely reduce code duplication is to obtain additional template parameter packs, particular a sequence of integer indices, needed to specify a member initializer:

    For example:

    struct constant_t;
    
    template 
    struct Array {
        T data[N];
        template 
        constexpr Array(constant_t, T const &value, std::index_sequence)
            : data { (Is,value)... }
        {}
    
        constexpr Array(constant_t, T const &value)
            : Array(constant_t{}, value, std::make_index_sequence{})
        {}
    };
    

    In this way we can define a constructor that initializes the array to a constant value without first default initializing each element. The only other way to achieve this, as far as I know, would require sticking the data member in a base class.

    Of course, better language support for template parameter packs might make this unnecessary.

提交回复
热议问题