2016-04-28 77 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