模板参数包访问第N个类型和第N个元素 [英] template parameter packs access Nth type and Nth element
问题描述
以下论文是我发现的有关模板参数包的第一个建议。
The following paper is the first proposal I found for template parameter packs.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1603.pdf
在第16页,它讨论引入两个新的运算符[]和<>来访问参数包元素和参数包类型。
At page 16, it talks about introducing two new operators [] and <> for accessing parameter pack elements and parameter pack types.
为此类运算符建议的语法包括两个新的运算符:。[]访问值和。<访问类型。例如:
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]; }
这些运算符在哪里?如果不存在,则它们的替代品是什么?
So where are these operators? If there is none, what is their replacement?
推荐答案
C ++ 11没有相应的运算符,这就是它们的原因被提议。使用C ++ 11,您需要自己提取相应的信息,或者使用已经执行了必要操作的类。最简单的方法可能只是使用已经实现了相应逻辑的 std :: tuple< T ...>
。
C++11 doesn't have corresponding operators which is the reason they are proposed. With C++11 you'll need to either extract the corresponding information yourself or use a class which already does the necessary operation. The easiest approach is probably to just use std::tuple<T...>
which already implements the corresponding logic.
如果您想知道 std :: tuple< T ...>
当前如何实现这些操作:基本上,这是使用相当差的函数进行函数编程的一种练习编程符号。一旦您知道如何获取序列的第 n
个类型,就可以使用从继承中获取第 n
个元素在索引和类型上参数化的基类相当简单。实施类似 tuple_element< N,T ...>
的内容可能类似于:
If you wonder how std::tuple<T...>
currently implements these operations: it is basically an exercise in functional programming using a fairly bad functional programming notation. Once you know how to get the n
-th type of the sequence, getting the n
-th element using inheritance from base classes parameterized on index and type is fairly trivial. Implementing something like tuple_element<N, T...>
could look something like this:
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的东西实际上更具挑战性...>
正在创建一个索引列表,因此您获得了一个类型和整数的并行列表,然后可以对其进行扩展,例如,使用诸如此类的基类列表详细信息看起来完全不同,但是具有用于类型及其索引的并行参数包的基本思想将在某种程度上出现):
The actual more challenging bit in implementing something like std::tuple<T...>
is conjuring up a list of indices so you got a parallel list of type and integers which can then be expanded, e.g., for a list of base classes using something like (how the internal details look exactly will differ but the basic idea of having a parallel parameters packs for the types and their indices will be somehow there):
template <typename... T, int... I>
class tuple_base<tuple_types<T...>, tuple_indices<I...>>:
public tuple_field<T, I>... {
};
这篇关于模板参数包访问第N个类型和第N个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!