4

Bar次の設定で、派生クラス内の名前を参照できるようにするにはどうすればよいDerived<T>ですか?

template <typename T> struct Foo
{
    template <typename U> struct Bar { };
};

template <typename T> struct Derived : Foo<T>
{
    // what goes here?

    Bar<int> x;  // Error: 'Bar' does not name a type
};

試してみましusing Foo<T>::Bar;たが、役に立ちません。using単純な宣言を維持できるように、ネストされた基本テンプレートの名前を派生クラスに知らせることができる宣言はありBar<int> xますか?

と言えることはわかっていますがtypename Foo<T>::template Bar<int> x;、そのようなケースがたくさんあるので、コードに不必要に冗長な負担をかけたくありません。また、個別の " ints" も多数あるため、typedefネストされたテンプレート インスタンスごとに for each を使用することもできません。

また、現時点では GCC 4.7 も C++11 も使用できないため、テンプレート エイリアスのない「従来の」ソリューションが必要です。

4

3 に答える 3

6

C++11 では、エイリアス テンプレートを使用できます。

template <typename T> struct Derived : Foo<T>
{
  template<typename X> using Bar = typename Foo<T>::template Bar<X>;
  Bar<int> x;
};

編集

従来の解決策は、すでに言われていることtypename Foo<T>:template Bar<int>、または「テンプレート typedef」をエミュレートすることです。

template <typename T> struct Derived : Foo<T>
{
  template<typename X>
    struct Bar
    { typedef typename Foo<T>::template Bar<X> type; };
  typename Bar<int>::type x;
};

言語にエイリアス テンプレートを追加する理由の 1 つは、C++03 では簡単に表現できないものをサポートすることです。

于 2012-05-17T18:02:41.463 に答える
1

宣言xするFoo<T>::Bar<int> x;だけでうまくいきます。

于 2012-05-17T17:50:36.510 に答える
0

これは機能します:

template <typename T> struct Foo
{
    template <typename U> struct Bar { };
};

template <typename T> struct Derived : Foo<T>
{
    template<class W>
    struct Bar : public Foo<T>::template Bar<W> {

    };

    Bar<int> x;  
};

それがあなたが探しているものならIDKですが、コンパイルします。

于 2012-05-17T18:07:23.650 に答える