我有两节课(这是我更实际的案例的摘录)
class ClUInt {
public:
ClUInt() : _i(2), _arr{1,2,3} {};
ClUInt(const unsigned int ui) : _i(ui) {};
private:
unsigned int _i;
double _arr[3];
};
class ClInt {
public:
ClInt() : _i(-2), _arr{-1,-2,-3} {};
ClInt(const int i) : ClInt() { _i = i; };
private:
int _i;
double _arr[3];
};
它们非常相似,但是其中一个使用
int
,另一个使用unsigned int
作为成员_i
。我想用以下方式重载
operator<<
:std::ostream& operator<<(std::ostream& os, const ClInt & ci)
{
cout << ci._i << endl;
cout << ci._arr[0] << endl;
return os;
}
假设我要两个类都“相同”重载。
我怎么只能写一次,所以更容易维护?
我曾想过要定义自己的 Actor 表,但我不确定这是走的路...
笔记:
struct
,所以如果隐私影响答案,则可以假定_i
和_arr
为public
。 struct
具有更多的“公共(public)”成员,它们分别是已签名/未签名的。 最佳答案
使用具有概念的模板:
#include <concepts>
#include <iostream>
template<typename T>
concept ClInteger = std::same_as<T, ClInt> || std::same_as<T, ClUInt>;
template <ClInteger T>
std::ostream& operator<<(std::ostream& os, const T & ci)
{
std::cout << ci._i << '\n';
std::cout << ci._arr[0] << '\n';
return os;
}
请注意,此运算符必须是这些类的 friend 才能访问其私有(private)字段。
LIVE