I've got a interface that's implemented as an abstract base class with a number of pure virtual public methods. These pure virtual functions can be implemented using a template since the differences between subclasses aren't large - so my idea was to use multiple inheritance to mix-in the appropriately templated helper-class that provides the implementation. However, the compiler complains that the base class is abstract; it isn't considering the helper mix-in's implementation so thinks there's no implementation of a required method.
For example:
class TrivialList {
int count;
public:
TrivialList(int count) : count(count){}
virtual double Average() const=0;
int Count() const {return count;}
virtual ~TrivialList(){}
};
template<typename TIndexable> class AverageHelper {
public:
double Average() const {
TIndexable const & self = static_cast<TIndexable const &>(*this);
double sum=0.0;
for(int i=0;i<self.Count();++) sum += self.Get(i);
return sum / self.Count();
}
};
class IndexableList : public TrivialList, public AverageHelper<IndexableList> {
std::vector<double> backend;
public:
IndexableList(int count) : TrivialList(count), backend(count) { }
double & Get(int i) { return backend[i];}
double const & Get(int i) const { return backend[i];}
};
IndexableList * MakeList() {return new IndexableList(5);} //error!
// cannot instantiate abstract class
I'm using MSC 10.0 (Visual Studio 2010); the code fails with a similar error using g++ 4.5.
Get
or the real-world equivalents in my project cannot be virtual because they're extremely minor operations that need to be inlined for adequate performance (think put-pixel/get-pixel) - so I need the generic algorithms to be templated rather than generic via virtual function calls.