簡體   English   中英

如何在構造函數中傳遞 C++ 模板 class 成員的初始值設定項?

[英]How to pass initializers for the C++ template class member in the constructor?

假設我有以下 C++ class

template<uint32_t NUM_OF_POINTS>
class A
{

public:

struct Point {
  float x;
  float y;
};

// here I don't know how to pass the initializers for the private member
  A();

private:

  Point table[NUM_OF_POINTS];

};

我一直在尋找一種方法如何通過構造函數傳遞成員table的初始化程序,即我希望能夠這樣做:

A<4> a({{0.0, 0.0}, {1.0, 1.0}, {2.0, 2.0}, {3.0, 3.0}});

是否有可能在 C++ 中通過可變參數模板?

C++ 有可能嗎?

一種替代方法是采用Point (&&)[NUM_OF_POINTS]類型的參數,然后使用std::copy將值復制到成員變量

A(Point (&&arr)[NUM_OF_POINTS]) {
  std::copy(arr, arr + NUM_OF_POINTS, table);
}

演示

您可以將對Point的 C 風格數組的引用作為參數,並通過索引技巧復制初始化table

#include <cstdint>
#include <utility>

template <std::uint32_t NUM_OF_POINTS>
class A {
   public:
    struct Point {
        float x;
        float y;
    };

    A(Point const (&pts) [NUM_OF_POINTS])
        : A(pts, std::make_index_sequence<NUM_OF_POINTS>{})
    { }

   private:
    Point table[NUM_OF_POINTS];

    template <std::size_t ... I>
    explicit A(Point const (&pts) [NUM_OF_POINTS], std::index_sequence<I...>)
        : table{ pts[I]... }
    {  }
};

這種方法不需要Point是默認可構造的。

然后,您可以按如下方式構造A

int main()
{
    A<2>::Point pts[2]{};
    A<2> a (pts);

    A<2> b ({{0,0}, {0,0}});
}

順便說一下,通過使Point依賴於A ,您將擁有許多不相關的點類型,如A<1>::PointA<2>::Point等。

暫無
暫無

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

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