【问题标题】:C++ typedef and templates syntax?C ++ typedef和模板语法?
【发布时间】:2016-08-23 03:38:53
【问题描述】:

我在可变参数模板上阅读了这个tutorial,但在下面的代码中:

 template<int index, class C>
struct container_index {

  // points to the "next" container type 
  typedef typename container_index<
    index-1,
    typename C::base_container
  >::container_type container_type;

  // points to the next T-type 
  typedef typename container_index<
    index-1,
    typename C::base_container
  >::type type;
};

这些 typedef 似乎是多余的,但它编译得很好。问题只是我不明白他们为什么会这样,我也没有找到解释这个案例的教程。有人可以给出一些解释吗?为什么重复 typedef 名称:

"::container_type container_type;"

 "::type type;"

不可能是这样的:

typedef typename container_index<
        index-1,
        typename C::base_container
      >  type;

非常感谢。

【问题讨论】:

标签: templates c++11 typedef variadic


【解决方案1】:

该示例演示了模板中的递归类型定义。关键是递归基本情况被指定为 index=0 的特化:

template<class C>
struct container_index<0, C> {

    // point to C instead of C::base_container
    typedef C container_type;

    // point to C::type instead of C::base_container::type
    typedef typename C::type type;
};

正是这种基本情况使得类型推导成为可能。例如,类型 container_index::container_type 被扩展为 container_index::container_type,后者又扩展为 container_index::container_type,最终扩展为 MyCont。

【讨论】:

  • 我现在明白了。只要“C”类有这个“类型”(如 typedef T 类型),所有类型推导都会发生。这部分让我更加困惑。谢谢你们!
【解决方案2】:

typedef 为类型命名。所以你需要提供你想给它的类型和名称。

typedef typename container_index&lt;index-1, typename C::base_container&gt;::type type;

typename container_index&lt;index-1, typename C::base_container&gt;::type 是我们描述我们想要命名的类型,而分号前的最后一个 type 是我们想要命名的名称。

比较:

struct Example
{
    typedef Fruit::orange citrus; // declare a type called Example::citrus, which is the same type as Fruit::orange
    typedef Fruit::apple apple; // declare a type called Example::apple, which is the same type as Fruit::apple - the same operation as the line above, and so the same syntax!
};

【讨论】:

  • 我不明白的是,程序员似乎在定义一个不存在的类型: typedef typename container_index::type type;程序员正在根据 container_index 模板中不存在的名为“type”的旧类型定义名为“type”的新类型?
  • Sergio:本教程中稍远一点的专门化结构 container_index 提供了一个存在的具体类型作为起点,其他一切都通过改变它来定义。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
相关资源
最近更新 更多