我有一个类 A,它派生自类模板 B。A 有一个 B 需要使用的内部类,如果不能,那么设计就没有意义了。
template <typename child_t>
class B {
typename child_t::inner_t& some_func();
};
class A : public B<A> {
public:
class inner_t { };
};
但是,当我尝试这样做时,编译器告诉我 A 没有名为 inner_t 的成员。我的第一个猜测是,这是因为 A 只是部分定义,但这种模式一直在使用。有办法解决这个问题吗?
最佳答案
有几种方法可以解决这个问题。
使
B
使得A
不必派生自它。template <typename child_t> struct B1 { typedef typename child_t::inner_t inner_t; inner_t foo() { return inner_t(); } }; struct A1 { struct inner_t {}; };
然后,您可以像这样使用它:
B1<A1> obj1; A1::inner_t inner = obj1.foo();
在进行函数调用之前不要指望
A
的定义。template <typename child_t> struct B2 { void foo() { typedef typename child_t::inner_t inner_t; // Do something with inner_t() } }; struct A2 : public B2<A2> { struct inner_t {}; };
然后,您可以像这样使用它:
B2<A2> obj2; obj2.foo();
关于c++ - 从父模板中使用 child 的内部类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24153316/