模板参数包访问第N个类型和第N个元素

问题描述 投票:35回答:5

以下文章是我为模板参数包找到的第一个提案。

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1603.pdf

在第16页,它讨论了引入两个新的运算符[]和<>来访问参数包元素和参数包类型。

The suggested syntax for such an operator involves two new operators: .[] to access values and .<> to access types. For instance:

template<int N, typename Tuple> struct tuple_element;
template<int N, ... Elements>
struct tuple_element<tuple<Elements...> >
{
    typedef Elements.<N> type;
};

template<int N, ... Elements>
Elements.<N>& get(tuple<Elements...>& t)
{ return t.[N]; }

template<int N, ... Elements>
const Elements.<N>& get(const tuple<Elements...>& t)
{ return t.[N]; }

那么这些运营商在哪里?如果没有,他们的替代品是什么?

c++ c++11 variadic-templates
5个回答
23
投票

C ++ 11没有相应的运算符,这就是它们被提出的原因。使用C ++ 11,您需要自己提取相应的信息或使用已经执行必要操作的类。最简单的方法可能就是使用已经实现相应逻辑的std::tuple<T...>

如果你想知道std::tuple<T...>目前如何实现这些操作:它基本上是使用相当糟糕的函数式编程符号进行函数式编程的练习。一旦你知道如何获得n-th类型的序列,使用索引和类型参数化的基类的继承来获取n-th元素是相当简单的。实现类似tuple_element<N, T...>的东西可能看起来像这样:

template <int N, typename... T>
struct tuple_element;

template <typename T0, typename... T>
struct tuple_element<0, T0, T...> {
    typedef T0 type;
};
template <int N, typename T0, typename... T>
struct tuple_element<N, T0, T...> {
    typedef typename tuple_element<N-1, T...>::type type;
};

实现类似std::tuple<T...>的实际更具挑战性的一点就是构建一个索引列表,这样你就可以得到一个类型和整数的并行列表,然后可以扩展它,例如,使用类似内部细节看的基类列表确切地说会有所不同,但是对于类型及其索引具有并行参数包的基本思想将以某种方式存在):

template <typename... T, int... I>
class tuple_base<tuple_types<T...>, tuple_indices<I...>>:
     public tuple_field<T, I>... {
};

42
投票

其他人已经回答说可以通过std::tuple完成。如果要访问参数包的第N种类型,您可能会发现以下元函数:

template<int N, typename... Ts> using NthTypeOf =
        typename std::tuple_element<N, std::tuple<Ts...>>::type;

用法:

using ThirdType = NthTypeOf<2, Ts...>;

6
投票

访问第N个元素?

使用std::forward_as_tuple

template <int I, class... Ts>
decltype(auto) get(Ts&&... ts) {
  return std::get<I>(std::forward_as_tuple(ts...));
}

用法示例:

template<class...Ts>
void foo(Ts&&...ts){

  auto& first = get<0>(ts...);
  auto second = get<1>(ts...);

  first = 'H';
  second = 'E';

  (std::cout << ... << ts);
}

foo('h','e','l','l','o');
// prints "Hello"

这个答案是为了补充Emile Cormier的答案,它只给出了第n种类型。


5
投票

要从包中获取第N个元素,您可以编写:

选项1

使用tuple_element获取第N个元素的返回类型:

template<size_t index, typename T, typename... Ts>
inline constexpr typename enable_if<index==0, T>::type
get(T&& t, Ts&&... ts) {
    return t;
}

template<size_t index, typename T, typename... Ts>
inline constexpr typename enable_if<(index > 0) && index <= sizeof...(Ts),
          typename tuple_element<index, tuple<T, Ts...>>::type>::type
get(T&& t, Ts&&... ts) {
    return get<index-1>(std::forward<Ts>(ts)...);
}

// below is optional - just for getting a more readable compilation error
// in case calling get with a bad index

inline template<long long index, typename... Ts>
constexpr bool index_ok() {
    return index >= 0 && index < sizeof...(Ts);
}

template<long long index, typename T, typename... Ts>
inline constexpr
typename enable_if<!index_ok<index, T, Ts...>(), T>::type
get(T&& t, Ts&&... ts) {
    static_assert(index_ok<index, T, Ts...>(),
        "bad index in call to get, smaller than zero or above pack size");
    return t;
}

选项2

不使用元组,依赖于自动返回类型,特别是在C ++ 14上的decltype(auto)和使用enable_if作为模板参数而不是作为返回类型:

template<size_t index, typename T, typename... Ts,
    typename enable_if<index==0>::type* = nullptr>
inline constexpr decltype(auto) get(T&& t, Ts&&... ts) {
    return std::forward<T>(t); 
}

template<size_t index, typename T, typename... Ts,
    typename enable_if<(index > 0 && index <= sizeof...(Ts))>::type* = nullptr>
inline constexpr decltype(auto) get(T&& t, Ts&&... ts) {
    return get<index-1>(std::forward<Ts>(ts)...);
}

template<long long index, typename... Ts>
inline constexpr bool index_ok() {
    return index >= 0 && index < (long long)sizeof...(Ts);
}

// block (compilation error) the call to get with bad index,
// providing a readable compilation error
template<long long index, typename T, typename... Ts,
    typename enable_if<(!index_ok<index, T, Ts...>())>::type* = nullptr>
inline constexpr decltype(auto) get(T&& t, Ts&&... ts) {
    static_assert(index_ok<index, T, Ts...>(),
        "bad index in call to get, smaller than zero or above pack size");
    return std::forward<T>(t); // need to return something...
                               // we hope to fail on the static_assert above
}

用法示例:

template<size_t index, typename... Ts>
void resetElementN(Ts&&... ts) {
    get<index>(std::forward<Ts>(ts)...) = {}; // assuming element N has an empty ctor
}

int main() {
    int i = 0;
    string s = "hello";
    get<0>(i,2,"hello","hello"s, 'a') += get<0>(2);
    get<1>(1,i,"hello",4) += get<1>(1, 2);
    get<3>(1,2,"hello",i) += get<2>(0, 1, 2);    
    get<2>(1,2,s,4) = get<2>(0, 1, "hi");
    cout << i << ' ' << s << endl;    
    resetElementN<1>(0, i, 2);
    resetElementN<0>(s, 1, 2);
    cout << i << ' ' << s << endl;    

    // not ok - and do not compile
    // get<0>(1,i,"hello","hello"s) = 5;
    // get<1>(1,i*2,"hello") = 5;
    // get<2>(1,i*2,"hello")[4] = '!';
    // resetElementN<1>(s, 1, 2);

    // ok
    const int j = 2;
    cout << get<0>(j,i,3,4) << endl;

    // not ok - and do not compile
    // get<0>(j,i,3,4) = 5;    

    // not ok - and do not compile
    // with a readable compilation error
    // cout << get<-1>("one", 2, '3') << endl;
    // cout << get<3>("one", 2, '3') << endl;
}

码 选项1:http://coliru.stacked-crooked.com/a/60ad3d860aa94453 选项2:http://coliru.stacked-crooked.com/a/09f6e8e155612f8b


2
投票

我们可以实现一个简单的函数来直接获取第n个参数,而不需要任何递归调用,但在编译时需要很多纯类型操作。我们先来看一下关键代码:

template<class...Ts>
struct GetImp {
  template<class T, class...Us>
  static decltype(auto) impl(Ts&&..., T&& obj, Us&&...) {
    return std::forward<T>(obj);
  }
};

template<size_t n, class...Ts>
decltype(auto) get(Ts&&...args) {
  static_assert(n<sizeof...(args), "index over range");
  return Transform<GetImp, Before_s<n, Seq<Ts...>> >
    ::impl(std::forward<Ts>(args)...);
}

Transform意味着什么?

例如,如果我们有一个类型Tstd::tuple<int,double,float>,那么Transform<GetImp,T>将是GetImp<int,double,float>。请注意,我定义了另一个空结构“Seq”而不是std::tuple,以较少的编译时间执行相同的操作。(实际上它们都可以很快编译,但我想一个空结构会更有效)所以Before_s<n,Seq<Ts...>>生成一个Seq<?>然后我们将它转​​换为GetImp,这样我们就可以知道什么类型的[0]〜[n-1]参数,然后将它们删除以直接索引第n个参数。例如,Before_s<3,Seq<T0,T1,T2,T3,T4...>>Seq<T0,T1,T2>Before_s<2,Seq<T0,T1,T2,T3,T4...>>Seq<T0,T1>等。当我们使用一个元函数来实现另一个元函数以减少编译时间时,我们使用Before_s来处理我们的Seq类型以减少编译时间。

履行

#define OMIT_T(...) typename __VA_ARGS__::type

template<class...Args>
struct Seq { };

template< template<class...> class Dst >
struct TransformImp{
    template< template<class...>class Src, class...Args >
    static Dst<Args...> from(Src<Args...>&&);
};
template< template<class...> class Dst, class T>
using Transform = decltype(TransformImp<Dst>::from(std::declval<T>()));
template<class T>
using Seqfy = Transform<Seq, T>;


template<class...>struct MergeImp;
template<class...Ts, class...Others>
struct MergeImp<Seq<Ts...>, Seq<Others...>>
{
  using type = Seq<Ts..., Others...>;
};
template<class first, class second>
using Merge = OMIT_T(MergeImp<Seqfy<first>, Seqfy<second> >);
template<class T, class U>
using Merge_s = OMIT_T(MergeImp<T, U>);

template<size_t, class...>struct BeforeImp;

template<size_t n, class T, class...Ts>
struct BeforeImp<n, Seq<T, Ts...>> {
    static_assert(n <= sizeof...(Ts)+1, "index over range");
    using type = Merge_s<Seq<T>, OMIT_T(BeforeImp<n - 1, Seq<Ts...>>)>;
};

template<class T, class...Ts>
struct BeforeImp<1, Seq<T, Ts...>> {
    using type = Seq<T>;
};
template<class T, class...Ts>
struct BeforeImp<0, Seq<T, Ts...>> {
    using type = Seq<>;
};
template<size_t n>
struct BeforeImp<n, Seq<>> {
    using type = Seq<>;
};

template<size_t n, class T>
using Before = OMIT_T(BeforeImp<n, Seqfy<T>>);
template<size_t n, class T>
using Before_s = OMIT_T(BeforeImp<n, T>);

编辑:高级实施

我们不需要使用Before_s来计算第n个类型之前的n-1类型,相反,我们可以忽略它们:

struct EatParam{
    constexpr EatParam(...)noexcept{}
};

template<size_t n>
struct GenSeqImp {
  using type = Merge_s<OMIT_T(GenSeqImp<n / 2>), OMIT_T(GenSeqImp<n - n / 2>)>;
};
template<>
struct GenSeqImp<0> {
  using type = Seq<>;
};
template<>
struct GenSeqImp<1> {
  using type = Seq<EatParam>;
};

template<size_t n>
using GenSeq = OMIT_T(GenSeqImp<n>);


template<class...Ts>
struct GetImp {
  template<class T>
  static constexpr decltype(auto) impl(Ts&&..., T&& obj, ...)noexcept {
    return std::forward<T>(obj);
  }
};


template<size_t n, class...Ts>
constexpr decltype(auto) get(Ts&&...args)noexcept {
  static_assert(n<sizeof...(args), "index over range.");
  //return Transform<GetImp, Before_s<n, Seq<Ts...>> >
  return Transform<GetImp, GenSeq<n>>
    ::impl(std::forward<Ts>(args)...);
}

另外,there是关于获得第n种类型的实现的一篇非常有趣的文章:

感谢他们的工作,我不知道我们之前可以使用(...)做黑客攻击。

© www.soinside.com 2019 - 2024. All rights reserved.