【发布时间】:2018-02-16 18:12:47
【问题描述】:
我目前正在构建一个 BigInt 类,并且在重载运算符 & 时,|和 ^,它们都将具有相似的函数语法,我想知道是否可以将运算符本身模板化为:
template<operator K>
BigInt operator K( const BigInt& a, const BigInt& b )
{
BigInt Result = 0;
uint64_t Max = max(a.GetSize() , b.GetSize()) /* max(a,b) is defined outside */
for (uint64_t n=0; n < Max; n++)
{
Result[n] = a[n] K b[N];
}
return Result;
}
其中 A[n] 返回一个带有 A 的第 n 位(二进制)的布尔值,并将其应用于运算符 &、|和 ^,这样我就不会写 3 个除了 2 个字母外相同的运算符重载。
我知道这种语法不起作用,但我想问是否有任何方法可以做您可能期望这种语法做的事情:用 &, | 替换 K或 ^ 且仅当您在代码中编写 (a & b) 时使用。
如果有帮助,这里是我对类的定义:
class BigInt
{
private:
vector<bool> num;
public:
/* Constructors */
BigInt();
template<class T> BigInt(T);
/* Class Methods */
void RLZ(); /* Remove Leading Zeroes */
uint64_t GetSize() const;
void print();
/* Operator Overloads */
std::vector<bool>::reference operator[] (uint64_t);
bool operator[] (uint64_t) const;
BigInt& operator=(const BigInt&);
};
【问题讨论】:
-
我认为您不能将运算符用作模板参数。我会等待有人证明我错了。
-
@RSahu: std::plus and friends :D
标签: c++ templates operator-overloading