在可强制转换为另一个模板类型的类模板中重载赋值操作符
Overloading assignment operator in a class template that can cast to another template type
#ifndef NUMBER_HPP
#define NUMBER_HPP
template <class T>
class Number
{
public:
Number( T value ) : m_value( value )
{
}
T value() const
{
return m_value;
}
void setValue( T value )
{
m_value = value;
}
Number<T>& operator=( T value )
{
m_value = value;
}
// template <class T2>
// Number<T2>& operator=( const Number<T>& number )
// {
// m_value = number.value();
// return *this;
// }
private:
T m_value;
};
typedef Number<int> Integer;
typedef Number<float> Float;
typedef Number<double> Double;
#endif // NUMBER_HPP
注释的赋值操作符重载是我想做的事情,我认为它可能比上面的代码片段提供更好的描述。
我希望能够做到以下几点:
Float a(10);
Integer b(20);
a = b;
其中a
将被强制转换为int
并给定b
的值,但仍然是Number
类的实例。
有可能吗?你能帮我一下吗?
你应该这样做:
template <class T2>
Number<T>& operator=( const Number<T2>& number )
{
m_value = number.value();
return *this;
}
也就是说,在参数类型中使用T2
,而不是在返回类型中!
我宁愿使用不同的字母作为模板参数:
template <class U>
Number<T>& operator=( const Number<U>& number )
{
m_value = number.m_value; //I would also directly access the member variable!
return *this;
}
我认为,最好使用显式强制转换,如果你想使用类类型作为模板参数,其构造函数已声明为explicit
:
m_value = static_cast<T>(number.m_value);
顺便说一下,其他operator=
应该实现为:
Number<T>& operator=(T const & value ) //accept by const reference
{
m_value = value;
return *this; //you've to return!
}
您有一些T
s在错误的地方。应该是
template <class T2>
Number<T>& operator=( const Number<T2>& number )
{
m_value = number.value();
return *this;
}
这将允许您执行
Integer a(4);
Float b(6.2f);
a = b;
cout << a.value() << endl;
,它将打印6
,行为类似于您正在模仿的int
和float
类型。
相关文章:
- c++中的重载赋值操作符
- 复制构造函数,赋值操作符重载
- c++复制构造函数,重载赋值操作符,方法get()
- 赋值操作符重载
- 当类是子类时重载赋值操作符
- 模板类的重载赋值操作符
- 使用重载赋值操作符
- 类和向量的重载赋值操作符
- 在可强制转换为另一个模板类型的类模板中重载赋值操作符
- 无法重载赋值操作符
- c++ const重载赋值操作符机制
- 创建了自己的字符串类——重载赋值操作符和析构函数的错误
- 在重载赋值操作符内调用构造函数
- 使用重载赋值操作符克隆单链表
- 类型演绎的重载赋值操作符
- 重载赋值操作符,留下基本功能
- 重载赋值操作符总线错误
- 退出重载赋值操作符将调用析构函数来删除对象
- 重载赋值操作符而不知道类结构
- 重载赋值操作符和其他操作符的区别是什么?