我想知道以下是否可行。 假设我有这样的代码:
template <class NumberType>
struct Number
{
NumberType value;
void operator = (Number in_val)
{
value = in_val;
}
}
那么我就可以做类似的事情:
Number<int> n1, n2;
n2.value = 5;
n1 = n2;
cout << "Value: " << n1.value << endl;
但这不允许我做以下事情:
Number<int> n1;
Number<double> n2;
n2.value = 5;
n1 = n2;
cout << "Value: " << n1.value << endl;
如何实现这一目标? 我是否必须将此结构/类包装为另一个或者我是否必须进行一些花哨的递归?
P.S。
我已经使用了C ++一段时间但从未尝试templates
。所以考虑一下我对模板很新。
- 编辑 - 好的,我现在正确了。但另一个相关问题来了。
template<class OtherNumType>
Number& operator *= ( const OtherNumType& in_value)
{
value *= in_value;
return *this;
}
这会产生编译错误。为什么?什么是正确的方法?
答案 0 :(得分:1)
您可以提供模板运算符=
template<class OtherNumType>
Number<NumberType>& operator= ( const Number<OtherNumType>& in_val)
{
value = in_val.value; // ok if the number types are implicitly convertable
return *this;
}
答案 1 :(得分:1)
当编译器为任何特定类型Number<T>
考虑T
的模板定义时,名称Number
(当用作类型名称时)被解释为Number<T>
},无论T
可能在那一点。
因此,对于Number<int>
,您当前的模板定义仅为下面的赋值运算符提供:
void operator=(Number<int> in_val)
因为此时Number
被解释为Number<int>
。
为了使操作员更灵活,您可以将其转换为成员模板(已模板化的类中的模板化函数):
template <class NumberType>
struct Number
{
NumberType value;
template <typename T2>
Number &operator=(const Number<T2> &in_val)
{
value = in_val.value;
return *this;
}
};
请注意我是如何修改操作符的,不仅要接受{em>任何类型的Number<T2>
T2
,还要让它返回*this
并接受参数为const引用 - 这是定义赋值运算符的最常用和最有用的方法。