是否可以将所有模板类型传递给运算符(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/