C++在给定基本元组类型和变元索引序列的情况下定义子元组类型

sg3maiej  于 5个月前  发布在  其他
关注(0)|答案(2)|浏览(55)

假设我有一个元组,例如using BaseTuple = std::tuple<int, double, string>;,我想从给定的可变参数索引序列中定义新的类型,以及从BaseTuple转换到BaseTuple的方法。例如,CustomTuple<0,1>应该从tuple<int,double>派生。

using BaseTuple = tuple<int, double, string>;

template <size_t... I>
struct CustomTuple: public tuple<tuple_element_t<I, BaseTuple>...>{
    using tuple<tuple_element_t<I, BaseTuple>...>::tuple;

    static CustomTuple fromBaseTuple(const BaseTuple& key){
        return {get<I>(key)...};
    };

    BaseTuple toBaseTuple(){
        BaseTuple t;
        ((get<tuple_element_t<I, BaseTuple>>(t) = get<tuple_element_t<I, BaseTuple>>(t)), ...);
        return t;
    }
};

字符串
如果tuple有唯一的类型,上面的代码就可以工作,但是我想知道是否有任何方法可以处理重复的类型。我找不到一种方法来用它的索引来重复I.。

njthzxwz

njthzxwz1#

沿着这些线的东西:

template <std::size_t... S>
BaseTuple toBaseTuple(std::index_sequence<S...>) {
    BaseTuple t;
    ((std::get<I>(t) = std::get<S>(*this)), ...);
    return t;
}
BaseTuple toBaseTuple(){
    return toBaseTuple(std::make_index_sequence<sizeof...(I)>{});
}

字符串
Demo

cetgtptt

cetgtptt2#

您可以使用std::apply,从而避免查找每个对应元素的需要:

using type = std::tuple<std::tuple_element_t<I, BaseTuple>...>

constexpr auto toBaseTuple() const {
  BaseTuple to;
  std::apply(
      [&](const auto &...elements) { (..., (std::get<I>(to) = elements)); },
      static_cast<const type &>(*this));
  return to;
}

字符串
Try it on godbolt.org

相关问题