简体   繁体   English

带参数的 C++ 转换运算符

[英]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).我有 HSB 和 RGB 颜色的转换运算符,以及 RGBA 到 RGB 的转换操作符(通过删除 alpha),但是我很难从 RGB 转换为 RGBA,因为我需要能够提供 alpha 作为参数(而不是总是默认为一)。

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.但是,我更喜欢使用标准的 C++ 转换,所以我只是想知道是否有任何方法可以使用带参数的转换运算符。

This is literally what constructors are for.这实际上就是构造函数的用途。

Declare and define one.声明并定义一个。

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;
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM