【问题标题】:Pass all template types to operator without specifying all types将所有模板类型传递给运算符而不指定所有类型
【发布时间】:2019-04-01 12:48:56
【问题描述】:

是否可以将所有模板类型传递给运算符? __Depth 对象赋值运算符都已重载,我正在尝试重载颜色通道运算符,而不必编写每个颜色深度和通道组合。

struct Depth8
    {
        unsigned char Depth;

        void operator =(const Depth16& _Depth)
        {
            Depth = 255 * _Depth.Depth / 65535;
        }
    };
    struct Depth16
    {
        unsigned short Depth;

        void operator =(const Depth8& _Depth)
        {
            Depth = 65535 * _Depth.Depth / 255;
        }
    };


template<class __Depth>struct ColorRGB
    {
        __Depth R;
        __Depth G;
        __Depth B;

        void    operator =(ColorBGR& _Color) // << Want to do this instead of..
        {
            R = _Color.R;
            G = _Color.G;
            B = _Color.B;
        }

void    operator =(ColorBGR<__Depth>& _Color) // << this..
            {
                R = _Color.R;
                G = _Color.G;
                B = _Color.B;
            }

void    operator =(ColorBGR<Depth16>& _Color) // << or this..
            {
                R = _Color.R;
                G = _Color.G;
                B = _Color.B;
            }
    };
        };

【问题讨论】:

  • 可以使用编译器生成的拷贝构造函数/赋值。
  • 与您的问题无关,但这些标识符是 best avoided。另外,我不太明白你在问什么。你能澄清一下吗?您可以参考help centerHow to Ask 部分,了解如何改进您的问题。
  • 我试图在不指定模板 __Depth 的情况下重载赋值运算符,所有 __Depth 都是深度对象,例如 8bit、16bit 并且所有运算符都已重载。
  • @StoryTeller 我已经更新了,有没有新的亮点?
  • 我真的不知道这篇文章是关于什么的。修复损坏的代码示例后,它会完全按照您的意愿工作。 coliru.stacked-crooked.com/a/5b5e49b3043b2488

标签: c++ templates arguments operators overloading


【解决方案1】:

您可以为成员使用模板以避免重复:

template<class Depth>
struct ColorRGB
{
    Depth R;
    Depth G;
    Depth B;

    ColorRGB(const Depth& r, const Depth& b, const Depth& g) : R(r), G(g), B(b) {}

    // Allow conversion between different depths.
    template <class Depth2>
    ColorRGB(const ColorRGB<Depth2>& rhs) :
        R(rhs.R),
        G(rhs.G),
        B(rhs.B)
    {
    }


    template <class Depth2>
    ColorRGB& operator =(const ColorRGB<Depth2>& rhs)
    {
        R = rhs.R;
        G = rhs.G;
        B = rhs.B;
        return *this;
    }



    ColorRGB(const ColorRGB& rhs) = default;
    ColorRGB& operator =(const ColorRGB& rhs) = default;
};

模板版本不处理拷贝构造函数,还好默认一个就可以了。

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 2016-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多