Why would one use function pointers to member method in C++?

前端 未结 10 2158
情书的邮戳
情书的邮戳 2021-02-10 23:48

A lot of C++ books and tutorials explain how to do this, but I haven\'t seen one that gives a convincing reason to choose to do this.

I understand very well why functio

10条回答
  •  孤城傲影
    2021-02-11 00:38

    In the past, member function pointers used to be useful in scenarios like this:

    class Image {
        // avoid duplicating the loop code
        void each(void(Image::* callback)(Point)) {
            for(int x = 0; x < w; x++)
                for(int y = 0; y < h; y++)
                    callback(Point(x, y));
        }
    
        void applyGreyscale() { each(&Image::greyscalePixel); }
        void greyscalePixel(Point p) {
            Color c = pixels[p];
            pixels[p] = Color::fromHsv(0, 0, (c.r() + c.g() + c.b()) / 3);
        }
    
        void applyInvert() { each(&Image::invertPixel); }
        void invertPixel(Point p) {
            Color c = pixels[p];
            pixels[p] = Color::fromRgb(255 - c.r(), 255 - r.g(), 255 - r.b());
        }
    };
    

    I've seen that used in a commercial painting app. (interestingly, it's one of the few C++ problems better solved with the preprocessor).

    Today, however, the only use for member function pointers is inside the implementation of boost::bind.

提交回复
热议问题