在可转换为其他模板类型的类模板中重载赋值运算符 [英] 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
注释的赋值运算符重载是我的尝试
The commented assignment operator overloading is my attempt to do what I want, I thought it might provide a better description than the one above the snippet.
我想要能够执行以下操作:
I want to be able to do the following:
Float a(10);
Integer b(20);
a = b;
其中 a
int
并给定 b
的值,但仍然是 Number
。
Where a
then would be casted to an int
and given the value of b
, but still be an instance of class Number
.
有可能吗?你能帮我一下吗?
Is it possible? Can you help me out here?
提前感谢。
推荐答案
您应该这样做:
template <class T2>
Number<T>& operator=( const Number<T2>& number )
{
m_value = number.value();
return *this;
}
也就是说,使用 T2
在参数类型中,不在返回类型!
That is, use T2
in the parameter type, not in the return type!
我希望对模板参数使用不同的字母:
I would rather use different letter for template parameter:
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 如果你想使用类类型作为模板参数,并且其构造函数已声明为 explicit
:
I think, it is better to use explicit cast, if you want to use class type as template argument and whose constructor has been declared explicit
:
m_value = static_cast<T>(number.m_value);
顺便说一下, c> operator = 应该实现为:
Number<T>& operator=(T const & value ) //accept by const reference
{
m_value = value;
return *this; //you've to return!
}
这篇关于在可转换为其他模板类型的类模板中重载赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!