【发布时间】:2015-10-23 14:25:26
【问题描述】:
我正在尝试将 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。
【问题讨论】:
标签: c++ templates type-conversion