C++ 模板类在模板类型之间进行转换,但也专门
基本上我想做到这一点 但我希望赋值运算符或复制构造函数是专门的 例如,我有一个颜色类:C++ 模板类在模板类型之间进行转换,但也专门,c++,templates,C++,Templates,基本上我想做到这一点 但我希望赋值运算符或复制构造函数是专门的 例如,我有一个颜色类: template<typename T = float> class color { public: T r; T g; T b; T a; color(T R, T G, T B, T A) : r(R), g(G), b(B), a(A) { } }; 当它这样做时,c1中的数字除以255,得到0到1的等价值 到目前为止,我已
template<typename T = float>
class color
{
public:
T r;
T g;
T b;
T a;
color(T R, T G, T B, T A)
: r(R), g(G), b(B), a(A)
{
}
};
当它这样做时,c1
中的数字除以255
,得到0
到1
的等价值
到目前为止,我已经做到了:
template<typename U>
color<T>(color<U> c)
: r(c.r/255.0), g(c.g/255.0), b(c.b/255.0), a(c.a/255.0)
{
}
模板
颜色(c色)
:r(c.r/255.0)、g(c.g/255.0)、b(c.b/255.0)、a(c.a/255.0)
{
}
但这也会将一个float
实例除以255。我不知道如何专门化此构造函数(或赋值运算符),使其仅对int
到float
专门化有效。编辑
也许这确实解决了你的问题。您只需要将构造函数完全专用于转换color
->color
,反之亦然。这是允许的
#include <iostream>
using namespace std;
template<typename T>
class color
{
public:
T r,g,b,a;
color(T r, T g, T b, T a) : r(r), g(g), b(b), a(a) {}
template<typename OtherT>
color(const color<OtherT>&);
};
template<>
template<>
color<int>::color(const color<float>& other) :
r(other.r * 255),
g(other.g * 255),
b(other.b * 255),
a(other.a * 255)
{}
int main() {
color<float> c1 = { 1.0f, 1.0f, 1.0f, 1.0f };
color<int> c2 = c1;
cout << c2.r << " " << c2.g << " " << c2.b << " " << c2.a << endl;
return 0;
}
#包括
使用名称空间std;
模板
类颜色
{
公众:
tr,g,b,a;
颜色(tr,tg,tb,ta):r(r),g(g),b(b),a(a){
模板
颜色(const color&);
};
模板
模板
颜色::颜色(常量颜色和其他):
r(其他.r*255),
g(其他.g*255),
b(其他.b*255),
a(其他a*255)
{}
int main(){
颜色c1={1.0f,1.0f,1.0f,1.0f};
颜色c2=c1;
我想可能有办法专门为int和float创建一个复制构造函数;但我无法为它计算出正确的语法。@DavidMurphy,你可以这么做,但我不确定它是否真正达到了你想要的效果。稍后将发布示例。非常感谢;我更喜欢你是一个新选项,因为我不喜欢定义multiple类只适用于不同的类型。
#include <iostream>
using namespace std;
template<typename T>
class color
{
public:
T r,g,b,a;
color(T r, T g, T b, T a) : r(r), g(g), b(b), a(a) {}
template<typename OtherT>
color(const color<OtherT>&);
};
template<>
template<>
color<int>::color(const color<float>& other) :
r(other.r * 255),
g(other.g * 255),
b(other.b * 255),
a(other.a * 255)
{}
int main() {
color<float> c1 = { 1.0f, 1.0f, 1.0f, 1.0f };
color<int> c2 = c1;
cout << c2.r << " " << c2.g << " " << c2.b << " " << c2.a << endl;
return 0;
}
template<typename T> class base_color { ... common code between int and float };
class int_color : public base_color<int>
{
public:
int_color(const float_color&) { ... }
}
class float_color : public base_color<float>
{
public:
float_color(const int_color&) { ... }
}