Performing a member function for each object, separated by commas

Here is the relevant code from the full list :

#include "CImg.h" using namespace cimg_library; int main() { CImg<unsigned char> src("Tulips.jpg"); int width = src.width(); int height = src.height(); int depth = src.depth(); //New grayscale images. CImg<unsigned char> gray1(width,height,depth,1); CImg<unsigned char> gray2(width,height,depth,1); // ... (src,gray1,gray2).display("RGB to Grayscale"); } 

How the line works (src,gray1,gray2).display("RGB to Grayscale"); ? How does the display member function apply to each of the objects in a comma-separated list?

+4
source share
2 answers

CImg overloads operator, which returns a CImgList , which is a list containing two CImg objects defined as operands. This object also overloads operator, to add CImg objects to the list.

The expression (src,gray1,gray2) equivalent to ((src,gray1),gray2) . An internal set of parentheses (src,gray1) creates a CImgList , and then (...,gray2) adds gray2 to this list, returning a link to the same list. CImgList has a display member function.

+2
source

Saying that the overload operator, () necessarily implies that an ugly design is stupid. There are many useful and smart ways to overload this statement, and CImg does it perfectly. Can you imagine that the C ++ standard would allow it if it was always β€œstupid”, as you say? In this example, C ++ code reads very well, it is definitely simpler (but equivalent) than writing CImgList (SRC, GRAY1, gray2) .display ();

Since CImg is a library for accelerating the writing of image processing algorithms (mainly used for prototyping), this design is definitely useful.

0
source

All Articles