模板类型转换操作符=

Templated type conversion operator =

本文关键字:操作符 类型转换      更新时间:2023-10-16

我正试图让类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。

这里有两个问题。第一:

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

你需要的是转换"复制"构造函数

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

当你写这样的代码:

A x = {a};

您实际使用的是构造函数(以a为参数),而不是赋值操作符。

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

的例子:

operator B() {
   B b;
   b.populate_from(this);
   return b;
}