I have C++11 project that uses inheritance. Here is small fragment:
class ICountable{
public:
virtual ~ICountable(){}
unsigned getCount() const{
return _getCount();
}
bool isEmpty() const{
return _getCount() == 0;
}
private:
virtual unsigned _getCount() const = 0;
};
Suppose we have some LinkList that inherits from ICountable and implements _getCount(). Then you can make function like this:
void doSomething(ICountable &countable){
if (countable.isEmpty())
doSomethingElse();
}
...
LinkList ll;
doSomething(ll);
This is all very good, but there must be another way to do all this:
template <typename T>
void doSomething(T countable){
if (countable.isEmpty())
doSomethingElse();
}
...
LinkList ll;
doSomething(ll); // we do not even need to add <>
Template way is faster and probably easier to implement. std::vector and std::deque are like this as well.
However, how I can avoid code duplication - function isEmpty() must be pasted in all "list things".
I can imagine preprocessor #include or...
I can imagine decorator-like class that may implements all those sugar methods and to proxy the others:
template <typename T>
class List{
T list;
public:
unsigned getCount() const{
return list.getCount();
}
bool isEmpty() const{
return list.getCount() == 0;
}
...
}
What is better inheritance or templates, if there will be no runtime polymorphism?
Is there better way to avoid code duplication?
Aucun commentaire:
Enregistrer un commentaire