簡體   English   中英

std :: array派生類聚合初始化

[英]std::array derived class aggregate initialization

我正在做一個小助手類,該類派生自std::array 構造函數顯然不繼承,而是負責括號初始化的對象。 例如:

template<typename T, size_t size>
struct foo : std::array<T,size>
{
     foo(int a, int b)
     : std::array<T,size>{a,b}
     {
          //nothing goes here since constructor is just a dummy that 
          //forwards all arguments to std::array constructor
     }
}

int main()
{
     foo<int,2> myobj = {1,2}; //brace initialization calls custom constructor with inner elements as arguments
}

參數的數量必須完全匹配,因此我傾向於在構造函數中使用類似可變參數函數的參數(因為我不僅會每次都在數組中使用2個元素)。 使用這個,我如何將可變參數包轉發到std::array構造函數? 我願意接受其他支持初始化的方法,這些方法允許轉發到std::array構造函數。

注意: std::initializer_list需要運行時初始化,我正在尋找兼容編譯時/ constexpr的方法。 謝謝。

您可以使用完美轉發的構造函數:

template<class... U>
foo(U&&... u)
    : std::array<T, size>{std::forward<U>(u)...}
{}

我認為從標准容器中繼承不是一個好主意。

無論如何...

您可以使用可變參數模板,完善的轉發功能以及SFINAE來強加參數數量恰好為size

您還可以使constexprfoo構造函數,以便使constexpr foo對象成為可能。

舉個例子

#include <array>
#include <type_traits>

template <typename T, std::size_t S>
struct foo : public std::array<T, S>
 {
   template <typename ... As,
             typename std::enable_if<sizeof...(As) == S>::type * = nullptr>
   constexpr foo (As && ... as)
      : std::array<T, S>{ { std::forward<As>(as)... } }
    { }
 };

int main ()
 {
   //constexpr foo<int, 2u> myobj1 = {1}; // compilation error
   constexpr foo<int, 2u> myobj2 = {1, 2}; // compile
   //constexpr foo<int, 2u> myobj3 = {1, 2, 3}; // compilation error
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM