我有一个这样声明的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) {
  }
};

在这里,公共(public) ctor 将参数打包成一个引用元组(可能是 l,也可能是 r)。它还获得两组索引。

然后它将它发送到 magic<0> ctor,它对参数进行混洗,以便最后一个是第一个(假设索引是正确的)。
magic<1> ctor 首先获取 vector ,然后是坐标。

基本上我打乱了争论,所以最后一个成为第一个。
magic 的存在只是为了让我不必过多考虑重载解析,并明确我要转发给哪个 ctor。没有它它可能会工作,但是当我用 ctor 转发做一些疯狂的事情时,我喜欢标记。

关于c++ - 获取可变参数模板的 all-but-last 参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31255890/

10-11 23:19
查看更多