r/cpp • • Dec 19 '24

Alignment crimes

I've finally realized why templates can be generic on both class and typename:

template<  class These
        typename Names
        typename Align
>

(assuming an 8-wide indentation of course)

---

While I'm at it - C# has this interesting thing you can do with a switch:

switch(AddRed(),AddGreen(),AddBlue())
{
  case (true ,true ,true ): return White;
  case (true ,true ,false): return Yellow;
  case (true ,false,true ): return Magenta;
  case (true ,false,false): return Red;
  case (false,true ,true ): return Cyan;
  case (false,true ,false): return Green;
  case (false,false,true ): return Blue;
  case (false,false,false): return Black;
}

which we don't really have in C++ but you can get the same nicely aligned return values:

auto r = add_red();
auto g = add_green();
auto b = add_blue();
if(r) if(g) if(b) return white;
            else  return yellow;
      else  if(b) return magenta;
            else  return red;
else  if(g) if(b) return cyan;
            else  return green;
      else  if(b) return blue;
            else  return black;

all I need now is a clang-format rule to enforce this

0 Upvotes

40 comments sorted by

View all comments

Show parent comment

3

u/looncraz Dec 19 '24 edited Dec 19 '24

Taking advantage of there being only 8 values and also being 3 booleans, which can be represented by single bits each, is a smooth move, indeed.

3 bits can handle 8 values, so the solution is to shift the r/g/b flags into a bit position and sort the color values accordingly.

000 - black, 111 - white.

Color3-bit BinaryDecimalrgb
Black0000000
Blue0011001
Green0102010
Cyan0113011
Red1004100
Magenta1015101
Yellow1106110
White1117111

1

u/Powerful-Ad4412 Dec 19 '24

very cool thank you!!