Arnav Borborah Arnav Borborah - 1 month ago 5x
C++ Question

Advantages of calling named lambda in class constructor vs calling an actual private function

I was designing an

class, where four parameters needed to be passed to the class's constructor, to instantiate the class. The constructor looks like the one below:

RGBA(int red = 0, int green = 0, int blue = 0, int alpha = 255)
auto valid_color = [](int param) {return (param >= 0 && param <= 255) ? param : 0; };
m_red = valid_color(red);
m_green = valid_color(green);
m_blue = valid_color(blue);
m_alpha = valid_color(alpha);

As you can see above, I have used a lambda for each parameter to verify the passed paramater. This lead me to wonder, what advantages could such a lambda have over a function, such as this (declared
in the the interface):

int valid_color(int param)
return (param >= 0 && param <= 255) ? param : 0;

So my options are this:

  1. Keep using the lambda, and let the code be.

  2. Instead of a lambda, declare an actual function, like the one above, and use that.

  3. Just write it out completely for everything. (Slightly tedious and definitelt error-prone).

Which option seems the best, and why?


Well, if you use a lambda, you can't do this:

RGBA(int red = 0, int green = 0, int blue = 0, int alpha = 255)
    : m_red{valid_color(red)}
    , m_green{valid_color(green)}
    , m_blue{valid_color(blue)}
    , m_alpha{valid_color(alpha)}

This uses a constructor initialization list to initialize the members, rather than doing it within the constructor body.

Also, your member function should be a static member function. Or an internal global/namespace-scoped function. It doesn't use this.