![](/img/trans.png)
[英]How to forward C++ base & member initializers through a template constructor?
[英]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>::Point
、 A<2>::Point
等。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.