How to make an optional template parameter with the base class using CRTP in the following code ?
template <unsigned int BYTES, OPTIONAL typename DerivedPrinter = MonoPrinter> //DerivedPrinter should be optional. If it is not specified then it should default to MonoPrinter.
class MonoPrinter
{
protected:
unsigned char CtrlCodes[BYTES] = { 0xFF }; //A code to initialize the printer
public:
MonoPrinter()
{
}
DerivedPrinter& print(const char* d)
{
for (int i=0; i<sizeof(CtrlCodes); i++)
SendCtrlCode(CtrlCodes[i]); //Initialize the printer and send additional control codes for color, font, etc...
printf("Print Me: %s\n", d); //This would actually send the string of chars to the printer (not to stdout) for printing
return static_cast<DerivedPrinter&>(*this); //Return a reference to the Derived Printer a la CRTP
}
};
template <unsigned int BYTES>
class ColorPrinter : public MonoPrinter<BYTES, ColorPrinter>
{
public:
ColorPrinter() : MonoPrinter()
{
static_assert(sizeof(CtrlCodes) >= 4);
CtrlCodes[1] = 0xAA;
CtrlCodes[2] = 0xBB;
CtrlCodes[3] = 0xC0;
}
ColorPrinter& SetColor(unsigned char c)
{
CtrlCodes[3] = c;
return *this;
}
};
void main(void)
{
MonoPrinter<1> iMonoPrinter;
ColorPrinter<4> iColorPrinter;
iMonoPrinter.print("Hello World").print(" we have no color");
iColorPrinter.print("Hello World").SetColor(BLUE).print(" in Living Color");
}
P.S.
The above code is a contrived and abridged for simplicity.
The "BYTES" template parameter is not optional and it always must be specified.
I have other problems with this code, but the main one is how to make the "DerivedPrinter" template parameter optional, so it does not always have to be specified ...and when it is not - it should default to the base class itself.