用嵌套类继承模板类 [英] Inherit template class with nested class

查看:79
本文介绍了用嵌套类继承模板类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个从模板类A继承的类B.并且我希望B的嵌套类E作为此继承中的模板参数.更加直观:

I want to create a class B that inherits from template class A. And I want the B's nested class E to be the template parameter in this inheritance. More visually:

template <class T>
class A {
}

class B : public A<B::E> {
    class E {
        int x;
    }
}

class C : public A<C::E> {
    class E {
        int x;
        int y;
    }
}

我认为问题在于编译器在处理B的声明时不知道类B将具有嵌套类E,因为我遇到了错误:

I think the problem is that the compiler doesn't know that the class B will have a nested class E by the time it's processing the declaration of B, since I'm getting the error:

在"B"中没有名为"E"的成员

no member named 'E' in 'B'

我已经看到了这个类似的问题,但是我想确认在放弃这种方法之前没有直接解决此冲突的方法.

I've seen this similar question, but I would like to confirm that there's no direct solution to this conflict before giving up with this approach.

谢谢!

推荐答案

我认为无法直接完成.

一种明显的方法是像在其他一些命名空间中定义 B :: E C :: E (至少将它们排除在全局命名空间之外),然后在父"类中使用它们:

One obvious approach would be something like defining B::E and C::E in some other namespace (to at least keep them out of the global namespace), then use them inside of the "parent" classes:

template <class T>
class A { /* ... */ };

namespace B_detail {
    class E { /* … */ };
}

class B : public A<B_detail::E> { /* ... */ };

namespace C_detail {
    class E { /* ... */ };
}

class C : public A<C_detail::E> { /* ... */ };

视情况而定,您很有可能需要/想要声明B/C的 * _ detail :: E friend 的朋友.

Depending upon the situation, there's a decent chance you'd also need/want to declare *_detail::E a friend of B/C.

这篇关于用嵌套类继承模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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