【问题标题】:Manipulate function arguments of a variadic function template操作可变参数函数模板的函数参数
【发布时间】:2016-01-28 02:41:56
【问题描述】:

我有一对begin()/end() 方法声明如下:

template <typename... Ts>
Iterator begin(Ts... indices) const;

template <typename... Ts>
Iterator end(Ts... indices) const;

从逻辑上讲,end() 可以用begin() 来实现。具体来说,end(x, y, ..., z) 等价于begin(x, y, ..., z + 1)。那么,有没有一种干净的方法可以使用indicesx, y, ..., z 变成x, y, ..., z + 1,这样我就可以像实现end() 一样

template <typename... Ts>
Iterator end(Ts... indices) const {
  return begin(whatever to do with indices...);
}

【问题讨论】:

    标签: c++ c++14 variadic-templates template-meta-programming


    【解决方案1】:
    template <std::size_t...Is,class... Ts>
    Iterator end_impl(std::index_sequence<Is...>,Ts... indices) const{
      auto tup=std::tie(indices...);
      return begin(std::get<Is>(tup)..., std::get<sizeof...(Ts)-1>(tup)+1);
    }
    template <class... Ts>
    Iterator end(Ts... indices) const{
      return end_impl(std::make_index_sequence<sizeof...(Ts)-1>{}, indices...);
    }
    

    只需添加一些完美的转发和隐私。

    使用 C++14 但相对容易实现部分。

    【讨论】:

    • 我可能刚刚完成了indices + (Is == sizeof...(Is) - 1 ? 0 : 1) ...(并在end 中相应地使用index_sequence_for&lt;Ts...&gt;),但这更多的是风格问题。
    • 不需要完美转发,因为Ts... 都是简单的整数类型。解决方案摇滚!
    • @T.C.我更赞成您的解决方案,其中论点不通过std::tuple
    • @T.C.顺便说一句,应该是indices + (Is == sizeof...(Is) - 1 ? 1 : 0) ...
    • @Lingxi 对。这就是我没有运行它的结果:/
    猜你喜欢
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多