C++ 在泛型类中实现特定方法

C++ 在泛型类中实现特定方法,c++,templates,generics,types,template-specialization,C++,Templates,Generics,Types,Template Specialization,我有一个问题,在网上搜索了一段时间,但没有什么好结果 我有一个用于2D图片的通用类Image2D: template <typename TValue> class Image2D { public: typedef Image2D<TValue> Self; // le type de *this typedef TValue Value; // le type pour la valeur de

我有一个问题,在网上搜索了一段时间,但没有什么好结果

我有一个用于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 ); 
    }
...
};
这同样适用于无符号字符,但方法的核心不应相同

问题是我不知道如何专门化特定类型的泛型函数。我试图创建以下内容:

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类。但是这样做需要迭代器必须在这个专门的类中重新实现;所以我不能使用泛型类的迭代器

所以这些解决方案都不起作用,所以我请求帮助。。嘿,帮帮忙


我怎样才能做我想做的事呢?

如果我正确理解了你的问题,那么你可以采取一些方法。我认为您需要的是模板专门化。为此,您希望修改泛型类以包含要专门化的函数:

template <typename TValue>
class Image2D{
    //your original code here
    void sepiaFilter(Image2D<Value> img){}
};
在这种情况下,您可能希望修改它自己的成员,而不是所传递内容的成员


无论如何,我希望这回答了你的问题,祝你好运

谢谢你们的帮助!Bronicki的解决方案正在发挥作用。 在做了他说的话之后

void sepiaFilter() { ... }
这是一个很好的解决办法

我把它叫做

img.sepiaFilter();

在main方法中,img是一个Image2D实例。

我建议将sepiaFilter编写为一个独立的函数模板,而不是一个成员。然后,您可以很容易地为特定情况重载它。我不清楚您想要专门化Image2D::sepiaFilterImage2D的哪些情况。当TValue和Color是同一类型时?当其中一个或两个都是无符号字符时,您的sepiaFilter函数似乎不使用此选项。所以也许它不应该有一个单独的Image2D参数,或者它应该是静态的,或者它应该是n.m.建议的非成员?
//code before function definition
static void sepiaFilter(Image2D<Value>& img){
    //modify member values of img by reference
}
//code after function definition
//code before function definition
void sepiaFilter(){
    //modify member values of this
}
//code after function definition
void sepiaFilter() { ... }
img.sepiaFilter();