【发布时间】:2018-11-17 18:44:43
【问题描述】:
我有一个问题,在互联网上搜索了一段时间,但没有任何好的结果。
我有一个用于 2D 图片的通用类 Image2D:
template <typename TValue>
class Image2D
{
public:
typedef Image2D<TValue> Self; // le type de *this
typedef TValue Value; // le type pour la valeur des pixels
typedef std::vector<Value> Container; // le type pour stocker les valeurs des pixels de l'image.
Image2D( int w, int h, Value g = Value() )
: m_width(w), m_height(h), m_data(Container(w * h, g)) { }
struct Iterator : public Container::iterator
{
Iterator( Self & image, int x, int y )
: Container::iterator( image.m_data.begin() + image.index( x, y ) ) { }
};
Iterator begin()
{
return start( 0, 0 );
}
Iterator end()
{
return start( 0, h() );
}
Iterator start( int x, int y )
{
return Iterator( *this, x, y );
}
...
};
当我实例化该泛型类时,它使我能够为图片的像素选择特定类型,例如unsigned char 或Color(unsigned char, unsigned char, unsigned char)。
我需要为该类添加一个方法,其中某些类型的实现可能会有所不同:
template <typename TValue>
class Image2D
{
...
template <typename Color>
void sepiaFilter()
{
for(Iterator it = this -> begin(), itE = this -> end(); it != itE; ++it)
{
Color oldColor = *it;
Color newColor = oldColor;
newColor.red = std::min((oldColor.red * .393) + (oldColor.green * .769) + (oldColor.blue * .189), 255.0);
newColor.green = std::min((oldColor.red * .349) + (oldColor.green * .686) + (oldColor.blue * .168), 255.0);
newColor.blue = std::min((oldColor.red * .272) + (oldColor.green * .534) + (oldColor.blue * .131), 255.0);
*it = newColor;
}
}
...
};
同样适用于unsigned char,但方法的核心不应该相同。
问题是我不知道如何为特定类型专门化泛型函数。我试图创建这个:
template<>
class Image2D<Color>
{
template <typename Color>
void sepiaFilter()
{
for(Iterator it = this -> begin(), itE = this -> end(); it != itE; ++it)
{
Color oldColor = *it;
Color newColor = oldColor;
newColor.red = std::min((oldColor.red * .393) + (oldColor.green * .769) + (oldColor.blue * .189), 255.0);
newColor.green = std::min((oldColor.red * .349) + (oldColor.green * .686) + (oldColor.blue * .168), 255.0);
newColor.blue = std::min((oldColor.red * .272) + (oldColor.green * .534) + (oldColor.blue * .131), 255.0);
*it = newColor;
}
}
}
并创建另一个特定的 Image2D 类。但是这样做需要在那个专门的类中重新实现迭代器;所以我不能使用泛型类的迭代器。
所以这些解决方案都不起作用,所以我正在寻求帮助.. Heeeeelp!
我怎么能做我想做的事?
【问题讨论】:
-
我建议将 sepiaFilter 编写为独立的函数模板,而不是成员。然后,您可以轻松地在特定情况下重载它。
-
我不清楚您想专门研究
Image2D<TValue>::sepiaFilter<Color>(Image2D)的哪些案例。当TValue和Color是同一类型时?当其中一个或两个是unsigned char? -
另外,您的
sepiaFilter函数似乎没有使用this。所以也许它不应该有一个单独的Image2D参数,或者它应该是static,或者它应该是一个非成员,如 n.m.建议?
标签: c++ templates generics types template-specialization