我们如何在子类中键入或重新定义模板化嵌套类?

lei*_*iiv 7 c++ templates

考虑以下:

template <typename T>
class Base {
  public:
    template <typename U>
    class Nested { };
};

template <typename T>
class Derived : public Base<T> {
  public:
    //How do we typedef of redefine Base<T>::Nested?
    using Base<T>::Nested; //This does not work
    using Base<T>::template<typename U> Nested; //Cannot do this either
    typedef typename Base<T>::template<typename U> Nested Nested; //Nope..

    //now we want to use the Nested class here
    template <typename U>
    Class NestedDerived : public Nested { };

    //or like this:
    Nested<int> nestedVar; // obviously does not work
};
Run Code Online (Sandbox Code Playgroud)

如何在Derived类中使用模板化的嵌套类?在当前版本的C++标准中可以做到这一点吗?

Geo*_*che 10

实际上using像广告一样工作,它只是没有摆脱模板中的依赖名称问题,它当前不能直接别名模板(将在C++ 0x中修复):

template <class T>
struct Base {
    template <class U> struct Nested {};
};

template <class T>
struct Derived : Base<T> {
    using Base<T>::Nested;

    // need to prefix Nested with template because
    // it is a dependent template:
    struct X : Base<T>::template Nested<int> {};

    // same here:
    template<class U>
    struct Y : Base<T>::template Nested<U> {};

    // data member, typename is needed here:
    typename Base<T>::template Nested<int> data;
};

void f() { 
    Derived<int>::Nested<int> n; // works fine outside
}
Run Code Online (Sandbox Code Playgroud)

在模板中使用时还有另一种可能的问题Derived<T>::Nested,但同样是依赖名称问题,而不是与继承相关:

template<class T>
void g() {
    // Nested is a dependent type and a dependent template, thus
    // we need 'typename' and 'template':
    typedef typename Derived<T>::template Nested<int> NestedInt;
}
Run Code Online (Sandbox Code Playgroud)

请记住,依赖于模板参数的名称必须是

  • typename如果是依赖类型,则加前缀:typename A<T>::B
  • template如果是依赖模板,则直接加前缀:A<T>::template f<int>()
  • 两者都是: typename A<T>::template B<int>
  • typename 在基类列表中是非法的: template<class T> struct A : B<T>, C<T>::template D<int> {};