【发布时间】:2019-06-06 17:19:07
【问题描述】:
我希望可以编写一个模板类,它可以被几个特定类型的子类继承。我希望继承的方法和运算符返回子类的类型而不是父模板类型。如果我只需要修改一个基类,这是希望节省大量的开发和维护工作。
这是我已有的示例:
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
}
如您所见,Mono8Pixel 结构继承了接受TMonoPixel 的+ 运算符,但使用此运算符返回TMonoPixel<uint8_t> 而不是Mono8Pixel,因为它是在基类中定义的。
我打算使用这些结构来迭代图像中的像素:
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 ...
}
}
有没有办法只更改模板类以确保Mono8Pixel(2) + Mono8Pixel(2) 返回Mono8Pixel?
请注意,无论解决方案是什么,这些结构都必须保持标准布局,因为我希望使用它们。
【问题讨论】:
-
看看 CRTP。
-
不,运行时多态是不可能的。可以通过 CRTP 完成。
标签: c++ templates inheritance operator-overloading