【问题标题】:Template classes conversion between template types but also specialised模板类型之间的模板类转换还要专门化
【发布时间】:2015-03-22 01:58:37
【问题描述】:

基本上我想完成这个Conversion between 2 template types

但我希望赋值运算符或复制构造函数是专门的。

例如,我有一个颜色类:

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

一般情况下,floats 在01 之间需要颜色分量。但是,将组件提供为介于 0255 之间的数字通常更容易,因为这通常是您在 Photoshop 或 GIMP 中得到的。

所以,我希望此类的实例能够在 floatint 类型之间进行转换:

color<int> c1(255,234,122,14);
color<float> c2 = c1;

当它这样做时,c1 中的数字除以 255 得到 01 的等价物。

所以到目前为止我已经这样做了:

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)
{
}

但这也会将float 实例除以255。我不知道如何专门化此构造函数(或赋值运算符),使其仅对 intfloat 专业化有效。

【问题讨论】:

    标签: c++ templates


    【解决方案1】:

    编辑

    也许这确实可以解决您的问题。您只想完全专门化转换 color&lt;int&gt; -> color&lt;float&gt; 的构造函数,反之亦然。这是允许的。

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

    我认为我更喜欢我的旧答案,因为如果用户输入除 int 或 float 之外的模板参数,这将给出难以解释的错误。另一种方法非常明确。

    旧答案

    你想要的主要问题是你不能部分特化类模板中的单个方法。

    如果用于模板类颜色的仅有两个参数是 int 和 float,我会这样安排:有一个包含公共代码的基本模板类,以及从它派生并提供专用构造函数的两个类。

    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&) { ... }
    }
    

    【讨论】:

    • 我认为可能有一种方法可以将复制构造函数专门用于 int 和 float;但我无法找出正确的语法。
    • @DavidMurphy,你可以这样做,但我不确定它是否真的能达到你想要的。稍后将发布示例。
    • 非常感谢;我更喜欢你是新的选择,只是因为我不喜欢只为不同的类型定义多个类。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多