C++ 模板<运算符>

标签 c++ templates operator-overloading

我目前正在构建一个 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/

相关文章:

c++ - 删除不同线程中的对象会导致崩溃?

c++ - new char 实际上是否保证类类型的对齐内存?

c++ - 将模板嵌套类的方法定义移到声明之外

C# 字符串运算符重载

c++ - 将右值引用传递给 boost::in_place 函数

c++ - `class template Example<int>;` 语句对 C++11 意味着什么?

c++ - 使用模板在 C++ 中编写一个获取组件的方法

c++ - "operator !="应该始终通过 C++ 中的 "operator =="实现吗?

c++ - 重载运算符%

php - 当您可以用 <<< 和结束分隔符填充字符串时,这叫做什么?