Suppose a few class templates specializations have some common public interface. Is it possible to declare it just once?
Example:
// Example for a generator
class G
{
public:
double generate(int channel);
};
template <typename Generator>
class A
{
public:
double step();
protected:
Generator g;
};
template <typename Generator, bool fixedMono>
class B;
template <typename Generator>
class B<Generator,true> : public A<Generator>
{
};
template <typename Generator>
class B<Generator,false> : public A<Generator>
{
public:
void setNumChannels(int numChannels);
private:
int numChannels;
};
template<typename Generator>
double B<Generator,true>::step() { return A<Generator>::g.generate(0); }
template<typename Generator>
double B<Generator,false>::step()
{
double sum = 0;
for (int i = 0; i < numChannels; ++i)
sum += A<Generator>::g.generate(i);
return sum;
}
This fails because the compiler doesn't recognize step
being declared in the B
specializations (which indeed, it isn't).
In a non-toy example the common interface could be larger than just a single function, and repeating its declaration in all specializations would not be desirable.
Is there good way to specify the common interface just once?
Please note suggestions to refactor the above example so there is no need for the template specializations to have a common interface are irrelevant, unless the refactoring method is one which can always be used to eliminate such interfaces. The question is whether declaring such a common interface just once, in cases where it is needed, is technically possible.