2017-06-22 6 views
0

vadiadicテンプレートを使用してIntListクラスを定義しようとしていますが、構文に苦労しています。初期化する方法がわかりませんクラスフィールドバリデリックテンプレートを使用してC++でリストクラスを定義する

template <int...> 
struct IntList; 

template<> 
struct IntList<>{ 
    constexpr static bool empty = true; 
    constexpr static int size = 0; 
}; 

template<int Hd> 
struct IntList<Hd>{ 
    constexpr static bool empty = false; 
    constexpr static int size = 1; 
    constexpr static int head = Hd; 
    constexpr static IntList<> next = IntList<>(); 
}; 

template<int Hd, int... Rs> 
struct IntList<Hd, Rs...>{ 
    constexpr static bool empty = false; 
    constexpr static int size = sizeof ...(Rs); 
    constexpr static int head = Hd; 
    constexpr static IntList<Rs...> next = IntList<Rs...>(); 
}; 

マイリストクラスは、4つのフィールドを持っている、リスト内の最初の数やリストの「尾」を返す次のフィールドを返すヘッドフィールドで次のように

私の最新バージョンです。

2つ以上の数字と1つの数字を含むリストの2つの基本ケースと、先頭と次のフィールドを含まない空のリスト( "空のリスト"はそのうちの1つにアクセスしようとするとエラーが発生します)。

IntList<1, 2, 3>::next::next; 

私に次のエラーを与える:

error: 'IntList<1, 2, 3>::next' is not a class, namespace, or enumeration 
    IntList<1, 2, 3>::next::next; 

は、ヘッドと、通常の(非静的)フィールドとして、次のフィールドを定義しようとすると私のリストをテストしようとすると、ラインが

コンストラクタ内で初期化するとエラーになります。

invalid use of non-static data member 'IntList<1, 2, 3>::head' 
    IntList<1, 2, 3>::head; 

実際には、両方のフィールドを「静的」として定義する必要があります。

頭を定義する方法に関する入力&次のフィールド/私が間違っていることは、非常に感謝しています!

+1

多分、あいまいなオーバーロード状態です。 'IntList <1>'は 'struct IntList 'と 'struct IntList 'の両方で空の可変パラメータリストとマッチします。あなたは完全に2番目のテンプレート宣言を取り除くことができます。 –

+0

なぜあなたはこのすべてをしたいですか? – Walter

+2

[std :: integer_sequence](http://en.cppreference.com/w/cpp/utility/integer_sequence)があることは知っていますか? – MadScientist

答えて

5

おそらく、代わりに静的メンバの型を宣言します:

using next = IntList<Rs...>; 

Demo

+0

行を変更する: 'constexprの静的IntList 次= IntList ();エラーにあなたが示唆しているものを結果に' : 'エラー:宣言は何も宣言していません[-fpermissive] IntList <1, 2, 3> ::次: :next; ' – Alice312

+0

@ Alice312:デモリンクを追加しました。 – Jarod42

1

これは、約半数のコードでは、あなたが欲しいものを行う必要があります。今

template<int...> 
struct ints { 
    constexpr static bool empty = true; 
    constexpr static int size = 0; 
}; 

template<int I0, int... Is> 
struct ints<I0, Is...>{ 
    constexpr static bool empty = false; 
    constexpr static int size = 1+sizeof...(Is); 
    constexpr static int head = I0; 
    using next = ints<Is...>; 
}; 

using just_three = ints<1, 2, 3>::next::next; 
static_assert(std::is_same<ints<3>, just_three>::value, "{3}=={3}"); 

がそれをテストします。

Live example

関連する問題