Reputation: 239
When I inherit from a templated class and provide the argument during the inheritence, how do I have to handle functions from the parent class, which use the template argument?
For example with this class as the parent:
template<typename T>
class Parent {
public:
virtual T someFunction(const T& data);
};
and I try to inherit like this:
class CharVersion : Parent<char> {
public:
T someFunction(const T& t) override {
return 'c'
}
};
How can I get the function in the child to act like:
char someFunction(const char& t) override {
return 'c'
}
The compiler obviously doesn't know T
in the subclass, so how can I express this?
Upvotes: 0
Views: 49
Reputation: 816
class CharVersion : Parent<char> {
public:
T someFunction(const T& t) override {
return 'c'
}
};
should be
class CharVersion : Parent<char> {
public:
char someFunction(const char& t) override {
return 'c'
}
};
Upvotes: 1
Reputation: 131550
When you write Parent<char>
, the compiler effectively generates a class definition as if you had substituted char
into the template text. That is, behind the scenes it's as if the parent class of CharVersion
is the following template instantiation:
class Parent_char {
public:
virtual char someFunction(const char& data);
};
You can write your subclass just as if you were extending that class. (Of course, the name of the generated template instantiation is not Parent_char
, but that's unlikely to matter.)
Upvotes: 1