2016-04-28 78 views
1

我对可变参数模板阅读本tutorial,但在下面的代码:C++ typedef和模板语法?

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名称重复:

"::container_type container_type;" 

"::type type;" 

它不能就这样:

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

非常感谢。

+1

由于递归?另见[这个问题]中的讨论(http://stackoverflow.com/questions/36913554/c-typedef-and-templates-syntax)。 –

回答

1

的示例演示模板递归类型定义。关键是,递归基础案例被指定为索引= 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 < 2,MyCont> :: container_type扩展为container_index < 1,MyCont> :: container_type,它又扩展到container_index < 0,MyCont> :: container_type,最终扩展到MyCont。

+0

我现在明白了。只要“C”类有这个“类型”(如typedef T型),就会发生所有类型的扣除。 这部分让我更困惑。 谢谢你们! –

0

typedef给出一个类型的名称。所以你需要提供你想要的类型和名称。

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

typename container_index<index-1, typename C::base_container>::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! 
}; 
+0

什么我不是undestant是,它似乎是程序员typedefing不存在的类型: typedef typename container_index :: type type; 程序员正在根据名为“type”的旧类型在container_index模板中不存在的情况下typedefing名为“type”的新类型? –

+0

Sergio:专业化结构container_index <0, C>本教程中稍后的部分提供了一个具体的类型,它存在,作为一个起点,其他所有内容都通过修改来定义。 – moonshadow