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

2024-04-22

我有一个演员这样声明:

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) {
  }
};

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

然后将其发送到magic<0>ctor,它会打乱参数,使最后一个参数排在第一个(假设索引正确)。

The magic<1>ctor 首先获取向量,然后获取坐标。

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取可变参数模板的所有参数 的相关文章

随机推荐