c++ - 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 use virtual methods when base class templated? possible?
genericcolor *color = new cmykcolor();
code below doesn't work. think rgbcolor , cmykcolor have different base class , causes problem. there workaround?
you're right 2 derived classes have different base classes (different specializations of genericcolor
template). both happen define virtual function named invertcolor
, 2 not related far compiler concerned.
one solution move invertcolor()
own class , derive genericcolor<>
that. way, both rgbcolor
, cmykcolor
"mean same thing" when 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 don't need override here? }; // rest before
aschepler's comment separating out colorcomponents
instead , using multiple inheritance/composition seems idea too; better 1 if makes sense situation.
Comments
Post a Comment