模板类型转换操作符=
Templated type conversion operator =
我正试图让类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;
}
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++中的双指针类型转换
- 逐位操作的隐式类型转换
- 模板中的类型转换
- 在 C++(和 C)中进行类型转换时明显不一致
- 字符类型转换不兼容
- 将复杂的非基元C++数据类型转换为 Erlang/Elixir 格式,以使用 NIF 导出方法
- C++:用户定义的显式类型转换函数错误
- 模板类型转换操作符=
- 模板化操作符实例化和类型转换
- 类型转换操作符重载——Visual studio 2013内部错误
- 没有显式类型转换的操作符重载
- C/ c++中的显式类型转换操作符
- 没有调用类型转换操作符
- 类型转换操作符不用于强制类型转换,编译器不同
- 我可以添加自己的类型转换操作符,以便能够将c++对象转换为objective C吗?
- 如何在c++中定义默认类型转换操作符
- 具有构造函数类型转换和转换操作符的转换序列
- c++使用赋值操作符模拟类型转换