Consider the following example
template <typename T>
class A
{
typename T::x a; //not used
virtual typename T::x* function()=0;
};
class B:public A<B>
{
public:
typedef XXX x;
x obj;
x* function()
{
return &obj;
}
};
Here I want to use the the type B::x
inside class A
.
Is there any way to do this?
This doesn't work. In order to instantiate A
, the compiler needs to have at least a forward declaration of x
. But you cannot forward declare members of a type as this is an implementation detail of the type and would imply that you already know some parts about the class.
You could, however, try to pass the return type directly to A
and use this as the return type:
template <typename T>
class A
{
public:
typedef T ret_type;
virtual ret_type* function() = 0;
};
class B : public A<int>
{
public:
A::ret_type obj;
virtual A::ret_type* function() override
{
return &obj;
}
};
With this approach you could do this:
class X : public A<int> { ... };
class Y : public A<int> { ... };
A<int>* p1 = new X();
A<int>* p2 = new Y();
p1->function();
p2->function();
...making the baseclass much more useful.
A parent should not need to know anything about its children, otherwise inheritance becomes meaningless. In your case A
can be considered an interface and it makes sense that any class implementing the interface A<int>
will behave the same. Contrary, if you pass the child-class to A
, every interface implementation is different and unique, even though it might have exactly the same return types. If you really need this, consider making A
a utility class and embedding it inside the subclass as a member ("favor composition over inheritance").
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments