4

Here is the relevant code from the full listing:

#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 does the line (src,gray1,gray2).display("RGB to Grayscale"); work? How is the display member function applied to each of the objects in the comma-separated list?

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
Junk Mvg
  • 157
  • 2
  • 7

2 Answers2

2

CImg overloads operator, which returns a CImgList object which is a list containing the two CImg objects given as operands. That object also overloads operator, to allow CImg objects to be added to the list.

The expression (src,gray1,gray2) is equivalent to ((src,gray1),gray2). The inner set of parentheses, (src,gray1), create the CImgList, and then (...,gray2) appends gray2 to that list, returning a reference to the same list. CImgList has the member function display.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Good explanation for what seems a very ugly design. Overloading `operator,` like this seems like pure obfuscation evil to me. – Arne Mertz Jan 22 '13 at 14:08
0

Saying that overloading operator,() necessarily implies a ugly design is stupid. There are lot of useful and clever ways to overload this operator, and CImg does it perfectly well. Do you imagine that the C++ standard would allow it if it was always 'stupid' as you say ? In this example, the C++ code reads very well, it is definitely more simple (but equivalent) than writing CImgList(src,gray1,gray2).display();

As CImg is a library to speed up the writing of image processing algorithms (used mainly for prototyping), this kind of construction is definitely useful.

bvalabas
  • 29
  • 1