模板化类型转换运算符=

时间:2015-10-23 14:25:26

标签: c++ templates type-conversion

我正在尝试将类型R类型T转换为R类型S,反之亦然。 operator =转换可以通过简单的赋值工作,但是当它尝试在初始化器中使用它时,它会失败。为什么呢?

#include <array>

template<class T>
class Rectangle
{
public :

    Rectangle(T l, T t, T r, T b) : x1(l), y1(t), x2(r), y2(b) 
    {

    }

    template<class S>
    Rectangle<T> & operator = (Rectangle<S> const & o)
    {
        x1 = static_cast<T>(o.x1);
        y1 = static_cast<T>(o.y1);
        x2 = static_cast<T>(o.x2);
        y2 = static_cast<T>(o.y2);

        return *this;
    }

    T x1, y1, x2, y2;
};

int main(void)
{
    auto foo = Rectangle<float>(1.0f, 2.0f, 3.0f, 4.0f);
    auto bar = Rectangle<double>(1.0, 2.0, 3.0, 4.0);

    {
        foo = bar; // Converts, ok.
    }

    {
        auto arr = std::array<Rectangle<float>, 2>() = {{ 
            foo, 
            bar // Error - no appropriate default constuctor
        }};
    }

    return 0;
}

编辑:我正在使用Visual Studio 2013。

3 个答案:

答案 0 :(得分:3)

这里有两个问题。第一:

auto arr = std::array<Rectangle<float>, 2>() = ...

Rectangle<T>不是默认构造的,因此()不会起作用。考虑到第二个=,我怀疑这只是一个错字。一旦你解决了这个问题:

    auto arr = std::array<Rectangle<float>, 2>{{ 
        foo, 
        bar // Still error
    }};

现在,您有一个赋值运算符,但我们没有分配。我们正在建设中。所以你需要的是一个构造函数:

template <class S>
Rectangle(Rectangle<S> const& o)
    : x1(o.x1)
    , y1(o.y1)
    , x2(o.x2)
    , y2(o.y2)
{ }

答案 1 :(得分:1)

您需要的是转换&#34;复制&#34;构造

template<class S>
Rectangle(Rectangle<S> const & o) : Rectangle(o.x1, o.x2, o.y1, o.y2)

当您编写如下代码时:

A x = {a};

您实际上正在使用构造函数(a作为参数),而不是赋值运算符。

答案 2 :(得分:0)

要使A类可转换为B类,您需要定义转换运算符,而不是赋值运算符。

示例:

operator B() {
   B b;
   b.populate_from(this);
   return b;
}
相关问题