简体   繁体   English

可变数据结构模板实例化

[英]Variadic data structure template instantiation

The following web page has an example of a variadic data structure (a tuple) link .以下 web 页面有一个可变参数数据结构(元组)链接的示例。 I have a question on the following code, which is claimed to generate the following class hierarchy.我对以下代码有疑问,据称该代码会生成以下 class 层次结构。 My question is, how is the hierarchy generated?我的问题是,层次结构是如何产生的? I don't see where the new struct type<Ts...> is generated?我没有看到新的struct type<Ts...>是在哪里生成的? Thanks谢谢

template <class... Ts> struct tuple {};

template <class T, class... Ts>
struct tuple<T, Ts...> : tuple<Ts...> {
  tuple(T t, Ts... ts) : tuple<Ts...>(ts...), tail(t) {}

  T tail;
};

Class Hierarchy: Class 层次结构:

tuple<double, uint64_t, const char*> t1(12.2, 42, "big");
struct tuple<double, uint64_t, const char*> : tuple<uint64_t, const char*> {
  double tail;
}

struct tuple<uint64_t, const char*> : tuple<const char*> {
  uint64_t tail;
}

struct tuple<const char*> : tuple {
  const char* tail;
}

struct tuple {
}

There are two class templates here这里有两个 class 模板

template <class... Ts> struct tuple {}; #1

and

template <class T, class... Ts>
struct tuple<T, Ts...> : tuple<Ts...> { ... } #2

And what happens in this case is that #2 is considered more specialized so when you have在这种情况下发生的事情是#2被认为更专业,所以当你有

tuple<double, uint64_t, const char*> 

#2 gets stamped out giving you #2 被淘汰给你

struct tuple<double, uint64_t, const char*> : tuple<uint64_t, const char*> 

This keeps happening creating the chain that you have, until you get to这种情况不断发生,创建您拥有的链,直到您到达

struct tuple<const char*> : tuple {
  const char* tail;
}

and here : tuple has no parameters so the only template it can call is #1 which then generates the end case of这里: tuple没有参数,所以它唯一可以调用的模板是#1,然后生成

struct tuple {};

Whenever it is impossible to extract a single type out of the type list (that means that this list is empty), the following code takes effect:每当无法从类型列表中提取单个类型时(这意味着该列表为空),以下代码生效:

template <class... Ts> struct tuple {};

That is an empty struct that becomes the base for the rest of the classes.这是一个空结构,它成为类的 rest 的基础。

If there is at least one type, the compiler divides the list into class T and the rest (one type less in the list):如果至少有一种类型,编译器会将列表分为class T和 rest(列表中少一种类型):

template <class T, class... Ts>
struct tuple<T, Ts...> : tuple<Ts...> {
  tuple(T t, Ts... ts) : tuple<Ts...>(ts...), tail(t) {}

  T tail;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM