我们如何在子类中 typedef 或重新定义模板化嵌套类? [英] How do we typedef or redefine a templated nested class in the subclass?

查看:28
本文介绍了我们如何在子类中 typedef 或重新定义模板化嵌套类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下事项:

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
};

如何在派生类中使用模板化嵌套类?在当前版本的 C++ 标准中可以这样做吗?

How to use the templated Nested class in the Derived class? Is this possible to do in current version of C++ standard?

推荐答案

实际上 using 像宣传的那样工作,它只是没有摆脱模板中的依赖名称问题,它可以't 目前直接使用别名模板(将在 C++ 中修复 0x):

Actually using works as advertised, it just doesn't get rid of the dependent-name issue in the template and it can't currently alias templates directly (will be fixed in 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
}

在模板中使用 Derived 时,还有另一个可能的问题,但同样是依赖名称问题,与继承无关:

There is another possible gotcha when using Derived<T>::Nested in templates, but again that is a dependent-name issue, not inheritance-related:

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;
}

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

Just remember that names that depend on template arguments have to be

  • 如果是依赖类型,则以 typename 为前缀:typename A<T>::B
  • 如果它是依赖模板,则直接以 template 为前缀:A<T>::template f<int>()
  • 如果两者都有:typename A<T>::template B<int>
  • typename 在基类列表中是非法的:template结构A:B<T>,C<T>::模板D<int>{};
  • prefixed with typename if its a dependent type: typename A<T>::B
  • directly prefixed with template if its a dependent template: A<T>::template f<int>()
  • both if both: typename A<T>::template B<int>
  • typename is illegal in base-class-lists: template<class T> struct A : B<T>, C<T>::template D<int> {};

这篇关于我们如何在子类中 typedef 或重新定义模板化嵌套类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆