Reputation: 14593
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.
Upvotes: 1
Views: 2635
Reputation: 101565
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
.
Upvotes: 1
Reputation: 264381
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?
Upvotes: 1
Reputation: 881595
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<>
).
Upvotes: 6
Reputation: 23178
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.
Upvotes: 1