2016-04-28 17 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は、冗長なようだが、それはうまくコンパイルします。問題は単純に私はなぜ彼らがこのようなものなのか理解できず、私はこのケースを説明するチュートリアルを見つけられませんでした。誰かが何か説明をしてもらえますか? 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"クラスがこの "type"(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

私が知り得ないことは、プログラマが存在しない型をtypedefしているようだということです: typedef typename container_index :: type type; プログラマは、container_indexテンプレートに存在しない "type"という名前の古い型に基づいて "type"という名前の新しい型をtypedefしていますか? –

+0

Sergio:特殊化構造体container_index <0, C>チュートリアルの少し下に、具体的な型が用意されています。これは出発点として存在し、それ以外のものはそれを変更することで定義されます。 – moonshadow

関連する問題