I have a Textf
class that can store formatted text and its properties (which is only color right now). I then have a Header
class that derives from it and adds a dashed underline, has some extra attributes, etc.
Additionally, I have a separate println
class (used a class for partial specialization support). Among other types, I have added support for Textf
objects. Naturally, I assumed (as with functions) the compiler would match a Header
object with the Textf
template. Instead, I got MSVC error C2679 (using VS 2019), which is because the compiler defaulted to the original template definition (because the Textf
pattern was not matched since the object is a Header
object).
If I were to define another template specialization for every child class, both specializations would have the exact same behavior, making the code extremely redundant (especially if there were many child objects).
For clarity, here is some sample code:
template<class LnTy>
class println // Default template def
{
public:
println(LnTy line)
{
std::cout << line;
}
};
class Textf
{
protected:
std::string_view m_text;
Color m_text_color; // Color is a scoped enum
Color m_background_color;
public:
// Constructors, etc...
virtual void display() const
{
// Change color
// Diplay text
// Restore color
}
};
class Header : public Textf
{
private:
// 'U_COORD' is struct { unsigned X, Y; }
U_COORD m_text_start_location;
public:
// Constructors, etc...
void display() const override
{
// Change color
// Change cursor location
// Display text
// Display dashed underline (next line)
// Restore cursor location (next line)
// Restore color
}
};
template<>
class println<Textf> // Specialization for 'Textf'
{
println(Textf line)
{
line.display();
}
};
How do I take advantage of polymorphism in templates for a situation like this?
I've come across other questions and done some research, but it seems I was only able to find things about a child class is inheriting from a template parent class, which isn't my point of confusion here.
In case it helps, I'm using the Windows console API to change the text's colors.