获取可变参数模板的所有参数

jca*_*cai 4 c++ variadic-templates c++11

我有一个演员这样声明:

template<typename... Coords>
MyClass<T>(vector<T> values, Coords... coords) { /* code */ }
Run Code Online (Sandbox Code Playgroud)

我希望它看起来像这样:

template<typename... Coords>
MyClass<T>(Coords... coords, vector<T> values) { /* code */ }
Run Code Online (Sandbox Code Playgroud)

但标准要求可变参数是最后一个。如果我写类似的东西

template<typename... Args>
MyClass<T>(Args... coordsThenValues) { /* code */ }
Run Code Online (Sandbox Code Playgroud)

我将如何拆分coordsThenValues为最后一个参数包Coords... coords和最后一个参数vector<T> values

Yak*_*ont 6

你喜欢元组吗?

你觉得作为元组转发怎么样?

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) {
  }
};
Run Code Online (Sandbox Code Playgroud)

这里公共构造函数将参数打包到一个引用元组中(可能是 l,可能是 r)。它还获得两组索引。

然后它将它发送到magic<0>ctor,它对参数进行打乱,使最后一个位于第一个(假设索引正确)。

ctormagic<1>首先获取向量,然后获取坐标。

基本上我改变了争论,所以最后一个变成了第一个。

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