2016-06-17 7 views
1

私が達成しようとしているのは、 "柔軟な"最初の引数を持つテンプレートです(おそらく配列要素のようなものです。第1引数:std::vector)と第2引数。その2番目の議論では、数値(例:std::arrayのsizeパラメータのような)、または一般的なクラスのための特殊化が必要です。クラスFooについてはオブジェクトやintに特化できるテンプレートを書くにはN

、私は現在

template <typename T, template <typename> typename Y > class Foo{}; 

を持っている理由は、それは、私は、私は専門を書くことができると思うです:

template<typename T> class Foo<T, int N>{}; 

と、struct Bar{}与えられ、

template<typename T> class Foo<T, Bar>{}; 

しかし、コンパイラ(C++ 11、ideone.com)は、エラー指定された行に "error: template argument 2 is invalid"と入力します。

おそらく、私は未定義の宣言を間違って形成しました。それともこれも可能ですか?

+0

あなたが問題を引き起こしているコードを投稿する必要がありますが、それはあなたが後にしているものをあなたの質問から非常に明確ではありません... – Nim

+0

また、あなたはタイプミスを持っているものをコンパイルしないでください。 – NathanOliver

+0

実際、専門化はコンパイルされません。それは私の問題です! –

答えて

4

ヘルパーテンプレートを使用して整数をラップし、型に変換することができます。これは、例えばBoost.MPLによって使用されるアプローチです。

#include <iostream> 

template <int N> 
struct int_ { }; // Wrapper 

template <class> // General template for types 
struct Foo { static constexpr char const *str = "Foo<T>"; }; 

template <int N> // Specialization for wrapped ints 
struct Foo<int_<N>> { static constexpr char const *str = "Foo<N>"; }; 

template <int N> // Type alias to make the int version easier to use 
using FooI = Foo<int_<N>>; 

struct Bar { }; 

int main() { 
    std::cout << Foo<Bar>::str << '\n' << FooI<42>::str << '\n'; 
} 

出力:

Foo<T> 
Foo<N>

Live on Coliru

+2

またはテンプレートを使用してint_ = std :: integral_constant ; ' – Jarod42

関連する問題