stil
stil

Reputation: 5556

Using virtual methods in class derived from templated base class

Let's consider following example:

template<std::size_t F>;
class GenericColor
{
public:
    std::array<int, F> colorComponents;
    virtual void invertColor();
}

class RGBColor : public GenericColor<3>
{
    void invertColor();
}

class CMYKColor : public GenericColor<4>
{
    void invertColor();
}

How would I use virtual methods when my base class is templated? Is it even possible?

GenericColor *color = new CMYKColor();

Code below doesn't work. I think that RGBColor and CMYKColor have different base class and it causes the problem. Is there any workaround?

Upvotes: 1

Views: 69

Answers (2)

dlf
dlf

Reputation: 9373

You're right that the two derived classes have different base classes (different specializations of the GenericColor template). Both happen to define a virtual function named invertColor, but the two are not related as far as the compiler is concerned.

One solution would be to move invertColor() into its own class and derive GenericColor<> from that. That way, both RGBColor and CMYKColor would "mean the same thing" when they say invertColor.

struct IGenericColor
{
   virtual ~IGenericColor() = 0 {}
   virtual void invertColor() = 0;
};

template<std::size_t F>
class GenericColor : public IGenericColor
{
public:
    std::array<int, F> colorComponents;
    virtual void invertColor(); // maybe you don't need an override here?
};

// rest as before

aschepler's comment about separating out ColorComponents instead and using multiple inheritance/composition seems like a good idea too; probably a better one if it makes sense for your situation.

Upvotes: 4

mwigdahl
mwigdahl

Reputation: 16578

GenericColor is not a class, not the way you have the hierarchy defined above. You can generate GenericColor<> classes based on the class template, but each of them is a distinct class.

Virtual functions should work properly within the inheritance "silo" defined by each template specialization; in other words, CMYKColor::invertColor() should properly override GenericColor<4>::invertColor().

Upvotes: 2

Related Questions