来自另一个类的模板运算符专用化

Template operator specialization from another class

本文关键字:运算符 专用 另一个      更新时间:2023-10-16

所以我正在尝试更改operator+方法的行为,因为我需要在另一个类的方法中实现较少的方法。如果这里有人能帮我做以下一项或多项工作,我将非常有义务:

  1. 也许我一直搜索错了?如果是这样,指向正确答案或信息来源的链接会很棒。
  2. 编写这样的东西的一般方法?

该方案的一些代码示例:

class Rational
{
public:
    const Rational Rational::operator+(const Rational &other) const {
        Rational ans;
        ans._denominator = other.getDenominator() * getDenominator();
        ans._numerator = getNumerator() * other.getDenominator() +
            other.getNumerator() * getDenominator();
        ans.init_rational(); /* <-- This part formats the rational number
                                    every time so that it'd look like 1/2
                                    instead of 2/4(f.e). The purpose of the
                                    specialized method in the other class is
                                    to perform the trace() method where lots
                                    of x+x+x is performed, therefore it'd be
                                    slow and unnecessary to use
                                    "init_rational()" before it's done adding
                             */
        return ans;
    }
};

需要专用运算符 + 的类:

template <class T>
class Matrix
{
private:
    int rows, cols;
    vector<vector<T>> mat;
public:
    const bool trace(T& ans) const
    {
        if (_rows() != _cols())
        {
            ans = T();
            return false;
        }
        ans = T();
        for (int i = 0; i < _rows(); i++)
        {
            ans = ans + mat[i][i];
        }
        return true;
    }
}

顺便说一句,我想我想要完成的事情可以在没有我要求的专业化的情况下完成,而是针对整个Rational类型的专业化,这是这里的实际答案吗?或者我也在寻找一个选项?

PS:如果您觉得需要更多信息/方法,请询问:p

编辑:从我在这里得到的回应来看,我想我不应该按照我想要的方式去做,不过做这样的事情呢?

template <Rational>
    const bool trace(Rational& ans) const{
        if (_rows() != _cols()){
            ans = Rational();
            return false;
        }
        ans = Rational();
        for (int i = 0; i < _rows(); i++){
            //adding method implemented here or in a separate function in the Rational class
        }
        return true;
    }

你在问题的第一部分提出的要求确实不像巴里所说的那样有意义,考虑到你编辑的信息和评论,这也许是你想要的吗?

bool trace(Rational& ans) const{return true;}

然后

template<typename T>
bool trace(T& ans) const{return false;}

如果是这样,那么您已经非常接近了,只是您需要将模板声明放在顶部并作为泛型类型,而不是相反,您倾向于特定类型:)

不,在Matrix<Rational>上下文中调用时operator+(Rational, Rational)不能使它与从其他源调用时执行不同的操作。这没有多大意义,并且严重违反了任何封装概念。

如果您希望在 Matrix 中具有特殊逻辑

ans = ans + mat[i][i];

然后,您可以提供另一层间接寻址,以便内部Matrix可以针对Rational所需的内容执行正确的操作:

increment(ans, mat[i][i]);

哪里:

template <typename T>
class Matrix {
private: // <--
    template <typename U>
    void increment(U& lhs, const U& rhs) {
        lhs += rhs;
    }
    void increment(Rational& lhs, const Rational& rhs) {
        // do something else
    }
};