Search code examples
c++parametersoperator-overloadingconversion-operator

C++ conversion operator with parameter


Is there any way to define a conversion operator that takes a parameter?

Here is my use case:

class RGBColor
{
    operator RGBAColor (const float alpha = 1.0) const noexcept;
}

I have conversion operators to/from HSB and RGB colors, and RGBA to RGB (by dropping the alpha), but I'm having difficulty converting from RGB to RGBA since I need to the ability to supply the alpha as a parameter (rather than always defaulting to one).

I assume that I'm going to have to fall back to something like:

RGBAColor ToRGBAColor (const float alpha = 1.0) const noexcept;

However, I would prefer to use standard C++ conversion, so I'm just wondering if there's any way to use a conversion operator that takes a parameter.


Solution

  • There's no way to pass additional parameters to a cast operator. The syntax doesn't allow that.

    As mentioned in comments and in the other answer, provide an appropriate constructor instead:

    struct RGB {
        float r_;
        float g_;
        float b_;
    };
    
    struct RGBA : RGB {
        float alpha_;
    
        RGBA(const RGB& rgb) : RGB(rgb), alpha_(1.0) {}
        RGBA(const RGB& rgb, float alpha) : RGB(rgb), alpha_(alpha) {} // <<<<
        RGBA& operator=(const RGB& rgb) {
            *static_cast<RGB*>(this) = rgb;
            alpha_ = 1.0;
            return *this;
        }
    };