I am hoping that it is possible to write a template class that will be inherited for several type-specific sub-classes. I want the inherited methods and operators to return the type of the sub-class rather than the parent template type. This is in hopes of saving lots of development and maintenance effort if I only have to modify one base class.
Here is an example of what I have already:
template<typename T> struct TMonoPixel
{
T value;
TMonoPixel(T v) { value = v; }
// the template has some pure virtual functions here...
TMonoPixel operator+ (const TMonoPixel& other)
{ return TMonoPixel(value + other.value); }
}
struct Mono8Pixel : TMonoPixel<uint8_t>
{
using TMonoPixel::TMonoPixel; // I want to inherit the constructor
// each pixel type implements the virtual functions in the template
}
As you can see the Mono8Pixel struct inherits the +
operator which accepts TMonoPixel
, but using this operator returns TMonoPixel<uint8_t>
rather than Mono8Pixel
because it is defined in the base class.
I am planning to use these structs for iterating over pixels in an image:
Image* img; // img has an unsigned char* pointer to its pixel data
for (int row=0; row<img->height; row++) {
for (int col=0; col<img->width; col++) {
int i = (row*img->width + col);
Mono8Pixel* pixel = reinterpret_cast<Mono8Pixel*>(img->dataPtr + sizeof(unsigned char)*i);
// modify the pixel ...
}
}
Is there any way to change just the template class to ensure that Mono8Pixel(2) + Mono8Pixel(2)
is returning a Mono8Pixel
?
Note that whatever the solution is, these structs must maintain standard layout because of how I wish to use them.