Let's say we have a template class Area
, which has a member variable T area
, a T getArea()
and a void setArea(T)
member functions.
I can create an Area
object of a specific type by typing Area<int>
.
Now I have a class Rectangle
that inherits the Area
class. Since Rectangle
itself is not a template, I cannot type Rectangle<int>
.
How do I specialize the inherited Area
type for Rectangle
objects?
EDIT: Sorry, I forgot to clarify - my questions is whether it is possible to inherit Area without specializing it, so it is not inherited as Area of ints but as Area Rectangle can specialize the types for.
This question is related to
c++
templates
inheritance
class Rectangle : public Area<int> {
};
#include<iostream>
using namespace std;
template<class t>
class base {
protected:
t a;
public:
base(t aa){
a = aa;
cout<<"base "<<a<<endl;
}
};
template <class t>
class derived: public base<t>{
public:
derived(t a): base<t>(a) {
}
//Here is the method in derived class
void sampleMethod() {
cout<<"In sample Method"<<endl;
}
};
int main() {
derived<int> q(1);
// calling the methods
q.sampleMethod();
}
Make Rectangle a template and pass the typename on to Area:
template <typename T>
class Rectangle : public Area<T>
{
};
Rectangle
will have to be a template, otherwise it is just one type. It cannot be a non-template whilst its base magically is. (Its base may be a template instantiation, though you seem to want to maintain the base's functionality as a template.)
Are you just trying to derive from Area<int>
? In which case you do this:
class Rectangle : public Area<int>
{
// ...
};
EDIT: Following the clarification, it seems you're actually trying to make Rectangle
a template as well, in which case the following should work:
template <typename T>
class Rectangle : public Area<T>
{
// ...
};
Source: Stackoverflow.com