【发布时间】:2019-03-30 03:48:27
【问题描述】:
按照this particularly insightful answer 提供的指南,我编写了一个实现一些基本运算符重载的模板类:
template <typename _type>
class myClass {
// ...
template<_input_type> myClass<_type>& operator+=(const myClass<_input_type>& _other);
// ...
}
算术复合运算符写成成员:
template <typename _type>
template <typename _input_type>
myClass<_type>& myClass<_type>::operator+=(const myClass<_input_type>& _other) {
static_assert(std::is_arithmetic<_type>::value);
// do stuff
return *this;
};
和非复合运算符作为非成员:
template <typename _type, typename _input_type>
inline myClass<_type> operator+(myClass<_type>& _o1, myClass<_input_type> _o2) {
return _o1+=_o2;
};
但是,由于模板 myClass 可用于多种数据类型,其中一些非数字类型无法处理 +、-、* 或 / 运算符,以及这样我想知道将所有运算符重载代码实现为非成员函数的缺点是什么,例如我可以将它们全部放在一个单独的头文件中,只有在需要算术功能时才需要包含该头文件。我知道一种解决方案是定义一个新的class myNumericClass : public myClass,它只实现运算符重载,但这需要一个新的类型名并限制myClass 的多功能性。
【问题讨论】:
-
将运算符放在另一个标题中没有明显问题。恕我直言,这是一个很好的解决方案。继承方案不好。
标签: c++ class templates operator-overloading