我目前正在构建一个 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] 返回一个 bool 值,其中包含 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&);
};
最佳答案
一个想法是在运算符函数上定义一个模板化的辅助函数(因为您不能在运算符本身上模板化),然后在适当的 BigInt 运算符的定义中实例化您的模板.例如:
template <class OperatorFn>
BigInt bitwiseOperator(const BigInt& a, const BigInt& b) const
{
BigInt Result = 0;
uint64_t Max = max(a.GetSize(), b.GetSize());
for (uint64_t n=0; n < Max; n++)
{
Result[n] = OperatorFn{}(a[n], b[N]);
}
return Result;
}
BigInt operator&(const BigInt& a, const BigInt& b) const { return bitwiseOperator<std::bit_and<bool>>(a, b); }
BigInt operator|(const BigInt& a, const BigInt& b) const { return bitwiseOperator<std::bit_or<bool>>(a, b); }
BigInt operator^(const BigInt& a, const BigInt& b) const { return bitwiseOperator<std::bit_xor<bool>>(a, b); }
关于C++ 模板<运算符>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48832635/