如何使用运算符编写可继承的模板类



我希望可以编写一个模板类,该模板类将继承给几个特定于类型的子类。我希望继承的方法和运算符返回子类的类型而不是父模板类型。这是希望如果我只需要修改一个基类,可以节省大量的开发和维护工作。

这是我已经拥有的示例:

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(来完成。基本思想是这样的:

template<class Pixel> struct TMonoPixel {
    ...
    // not virtual
    std::string GetSomeProperty() const {
        return static_cast<const Pixel&>(*this).GetSomeProperty();
    }
    Pixel operator+(const TMonoPixel& other) const {
        return Pixel(value + other.value);
    }
};
struct Mono8Pixel : TMonoPixel<Mono8Pixel> {
    using TMonoPixel::TMonoPixel;
    std::string GetSomeProperty() const {
        return "My name is Mono8Pixel";
    }
};

多亏了隐式派生到基数的转换,现在你可以像这样使用它:

template<class T>
void foo(const TMonoPixel<T>& number) {
    std::cout << number.GetSomeProperty();    
}
Mono8Pixel i;
foo(i);

请注意,在 TMonoPixel 中,Pixel 是一个不完整的类型,因此您对如何使用它有一些限制。例如,您不能这样做:

template<class Pixel> struct TMonoPixel {
    Pixel::Type operator+(const TMonoPixel& other);
};
struct Mono8Pixel : TMonoPixel<Mono8Pixel> {
    using Type = std::uint8_t;
};

类型特征是克服这些限制的有用技术:

struct Mono8Pixel;
template<class Pixel> struct ValueType;
template<> struct ValueType<Mono8Pixel> {
    using Type = std::uint8_t;
};
template<class Pixel> struct TMonoPixel {
    using Type = typename ValueType<Pixel>::Type;
    Type value;
    TMonoPixel(Type value) : value(value)
    {}
    Pixel operator+(const TMonoPixel& other) const {
        return Pixel(value + other.value);
    }
};
struct Mono8Pixel : TMonoPixel<Mono8Pixel> {
    using TMonoPixel::TMonoPixel;
};

Mono8Pixel(2) + Mono8Pixel(2)的类型是 Mono8Pixel .

所以我想我是在问这些基于 CRTP 的结构在对value类型进行所有这些更改后是否具有标准布局。

他们确实:

static_assert(std::is_standard_layout_v<Mono8Pixel>);

完整示例:https://godbolt.org/z/8z0CKX

最新更新