派生类函数参数作为基类引用导致C2678

Derived class function parameter as base class reference is causing C2678

本文关键字:引用 C2678 基类 类函数 参数 派生      更新时间:2023-10-16

我创建了派生类,该类派生的是Base'类。它正在使用CRTP。基类包含一个一元运算符和一个二元运算符。派生类正在实现那些虚拟运算符函数。

template <typename T> class Base
{
public:
    virtual bool operator==(T operand) = 0;
    virtual bool operator!() = 0;
};
class Derived : public Base<Derived>
{
public:
    virtual bool operator==(Derived operand){ return true; }
    virtual bool operator!(){ return false; }
};

模板函数notf和equalf用于测试派生类的成员运算符。函数notf通过引用获取一个Base,并调用其!操作人员函数equalf做类似的事情。

template <typename T> bool notf(Base<T>& x)
{
    return !x;
}
template <typename T> bool equalf(Base<T>& x, Base<T>& y)
{
    return x == y;
}

主函数调用这些模板函数。

int main()
{
    Derived x, y;
    cout << notf(x);
    cout << equalf(x, y);
    return 0;
}

并且在equalf函数上产生C2678误差。编译器说,error C2678: binary '==' : no operator found which takes a left-hand operand of type 'Base<Derived>' (or there is no acceptable conversion)。但我不知道问题出在哪里,因为notf函数运行良好。当编译除equalf函数之外的代码时,它运行良好。

当我制作equalf函数来显示参数的类型时,它显示"class Derived"answers"class Derive"。如果是真的,那么为什么错误消息显示left-hand operand of type 'Base<Derived>'

Base<T>::operator==(T operand)不能接受Base<T>参数(因为没有定义转换)。

很难提出修复方案,因为代码指向许多可能的设计方向。

然而,无论如何,虚拟比较运算符或虚拟赋值的想法通常是不好的,因为它将类型检查转移到了运行时,因此您需要更多的测试和更复杂的代码。