views:

144

answers:

4

Is the following valid? Or how can I get something close to this.

template<class T_> class Template {
   //something
};

class Parent {
public:
   Template<Parent> variable;

   Parent() : variable(this) { }
};

class Derived : public Parent {
public:
   Template<Derived> variable;

   Derived() : Parent() { }
}

Thanks in advance.

+1  A: 

If you want to have a variable with the same name in a base and derived class you don't need templates.

Just define them and from derived access ->variable and ->Base::variable. Those are 2 different variables.

Arkaitz Jimenez
Therefore, base calling variable will get its own version.
Cem Kalyoncu
+5  A: 

It's technically "valid" in that your compiler has to accept it (it may warn you, and IMHO it should), but it doesn't do what you think it does: Derived's variable is separate from Parent's, and is not getting explicitly initialized (so it uses the default ctor for Template<>).

Alex Martelli
+1  A: 

Few minor types.
But the main problem was that Parent was using a constructor on Template that did not exist.

template<class T>
class Template
{
    public:
        Template()      {}  // Used in Derived
        Template(T* t)  {}  // Used in Parent
};

class Parent
{
    public:
       Template<Parent> variable;

        Parent() : variable(this)   {}
};

class Derived : public Parent
{
    public:
       Template<Derived> variable;

       Derived() : Parent()         {}
};

I am curious what you are trying to achieve though.
Is this some variation of the "Curiously Reoccurring Template" Pattern or something?

Martin York
Cem Kalyoncu
+1  A: 

You shouldn't get something close to this, because such a redefinition of a public variable violates Liskov Substitution Principle - your Derived becomes more restrictive than Parent, and cannot be substituted in its place, and therefore it shouldn't be in a superclass/subclass relation.

Furthermore, if it would allow you to redefine a field in a sense of actually reusing the same memory location somehow, then it would break the type system as well: all methods in Parent expect variable to be of type Template<Parent>; if it actually be an instance of Template<Derived>, there is no guarantee that Template<T> is covariant in T.

Pavel Minaev