簡體   English   中英

獲取可變參數模板的所有但最后一個參數

[英]Obtain all-but-last parameter of variadic template

我有一個ctor聲這樣:

template<typename... Coords>
MyClass<T>(vector<T> values, Coords... coords) { /* code */ }

我希望它看起來像這樣:

template<typename... Coords>
MyClass<T>(Coords... coords, vector<T> values) { /* code */ }

但是標准要求可變參數是最后一個。 如果我寫的東西像

template<typename... Args>
MyClass<T>(Args... coordsThenValues) { /* code */ }

我如何將coordsThenValues分成一個全部但最后一個參數包Coords... coords和最后一個參數vector<T> values

你喜歡元組嗎?

你覺得像元組一樣前進?

struct foo {
  template<class...Ts>
  foo(Ts&&...ts):
    foo(
      magic<0>{}, // sent it to the right ctor
      std::index_sequence< sizeof...(ts)-1 >{}, // the last shall be first
      std::make_index_sequence<sizeof...(ts)-1>{}, // the first shall be last
      std::forward_as_tuple(std::forward<Ts>(ts)...) // bundled args
    )
  {}
private:
  template<size_t>
  struct magic {};
  template<size_t...I0s, size_t...I1s, class...Ts>
  foo(
    magic<0>, // tag
    std::index_sequence<I0s...>, // first args
    std::index_sequence<I1s...>, // last args
    std::tuple<Ts&&...> args // all args
  ):
    foo(
      magic<1>{}, // dispatch to another tagged ctor
      std::get<I0s>(std::move(args))..., // get first args
      std::get<I1s>(std::move(args))... // and last args
    )
  {}
  // this ctor gets the args in an easier to understand order:
  template<class...Coords>
  foo(magic<1>, std::vector<T> values, Coords...coords) {
  }
};

在這里,公共ctor將參數打包成一個引用元組(可能是l,可能是r)。 它還有兩組索引。

然后它將它發送到magic<0> ctor,它將參數混亂,以便最后一個是第一個(假設索引是正確的)。

magic<1> ctor首先獲得向量,然后是coords。

基本上我改變了爭論,所以最后一個成為第一個。

magic只是為了讓我不必過多考慮重載決策,並讓我轉發到顯式的ctor。 如果沒有它,它可能會工作,但我喜歡標記,當我做ctor轉發瘋狂的事情。

暫無
暫無

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

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