c++ - 将所有模板类型传递给运算符而不指定所有类型

标签 c++ templates arguments operators overloading

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

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

最佳答案

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

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

模板版本不处理复制构造函数,但幸运的是,默认的就可以了。

关于c++ - 将所有模板类型传递给运算符而不指定所有类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031084/

相关文章:

c++ - 使用 KDevelop 4.4.1 的 undefined reference

c++ - UAC是否可以在不启动另一个进程的情况下提升一个进程

c# - 如何在不混淆 Razor 引擎的情况下正确呈现变量?

c++ - 二进制数据作为命令行参数

c++ - 高效的浮点比较(Cortex-A8)

c++ - 如何返回对非类型模板参数的默认值的引用

c++ - 运算符重载导致模板参数推导失败

node.js - 我尝试了一切方法使该模板正常工作,但仍然出现此错误 : Only named blocks and mixins can appear at the top level of an extending template

javascript - 在 Internet Explorer 中调试 JavaScript 时, "Invalid Argument"是什么意思以及导致此错误的原因是什么?

javascript - 从一个方法传递参数到另一个方法似乎不会改变 typescript 中的参数