[英]Variadic template constructor with multiple parameters packs
我已經讀過這個 , 這個 , 這個以及許多其他的......但這些帖子都沒有回答或適用於我的具體問題。
我有一個帶有可變參數模板構造函數的struct X
:
struct X
{
template<typename... T>
X(T... t) { /*...*/ }
};
我有一個結構Y
,它包含兩個X
類型的對象。 我想為Y
定義一個模板構造函數,允許使用不同的參數列表正確初始化類型X
兩個成員,即看起來像下面的代碼(顯然不起作用):
struct Y
{
template<typename... U, typename... V>
Y(U&&... u, V&&... v) // this does not work
: x1(std::forward(u)...), x2(std::forward(v)...) // this is was I need to do
{}
X x1, x2;
};
我怎么能這樣做,使用包裝器,元組或任何合適的元編程機制? C ++ 14解決方案是可以接受的。
沼澤標准index_sequence
技巧。
struct Y
{
private:
template<typename... U, typename... V,
std::size_t... UIs, std::size_t... VIs>
Y(std::tuple<U...>&& u, std::tuple<V...>&& v,
std::index_sequence<UIs...>, std::index_sequence<VIs...>)
: x1(std::get<UIs>(std::move(u))...),
x1(std::get<VIs>(std::move(v))...)
{}
public:
template<typename... U, typename... V>
Y(std::tuple<U...> u, std::tuple<V...> v)
: Y(std::move(u), std::move(v),
std::index_sequence_for<U...>{},
std::index_sequence_for<V...>{})
{}
X x1, x2;
};
在C ++ 17中,只需使用make_from_tuple
:
struct Y
{
public:
template<typename... U, typename... V>
Y(std::tuple<U...> u, std::tuple<V...> v)
: x1(std::make_from_tuple<X>(std::move(u))),
x2(std::make_from_tuple<X>(std::move(v)))
{}
X x1, x2;
};
使用元組是一個很大的開銷,因為它已經要求X可以移動/復制,你可以直接使用該約束,並獲得最可讀的代碼:
struct Y
{
Y(X && _x1, X && _x2)
: x1(std::move(_x1)), x2(std::move(_x2))
{}
X x1, x2;
};
在代碼中只寫:
Y y(X(args_x1...), X(args_x2...));
或者如果X有隱式構造函數:
Y y({args_x1...}, {args_x2...});
更有趣的問題是,如果X不可移動/可復制,但這超出了范圍;)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.