Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 作为基类引用的派生类函数参数导致C2678_C++_Templates_Inheritance_Crtp - Fatal编程技术网

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

C++ 作为基类引用的派生类函数参数导致C2678,c++,templates,inheritance,crtp,C++,Templates,Inheritance,Crtp,我创建了“派生”类,它派生“基类”。它正在使用CRTP。基类包含一个一元运算符和一个二元运算符。派生类正在实现这些虚拟运算符函数 template <typename T> class Base { public: virtual bool operator==(T operand) = 0; virtual bool operator!() = 0; }; class Derived : public Base<Derived> { public:

我创建了“派生”类,它派生“基类”。它正在使用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; }
};
int main()
{
    Derived x, y;
    cout << notf(x);
    cout << equalf(x, y);
    return 0;
}
模板类基类
{
公众:
虚拟布尔运算符==(T操作数)=0;
虚拟布尔运算符!()=0;
};
派生类:公共基
{
公众:
虚拟布尔运算符==(派生操作数){返回真;}
虚拟布尔运算符!(){return false;}
};
模板函数notf和equalf用于测试派生类的成员运算符。函数notf引用一个基,并调用它的!操作人员函数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;
}
模板布尔notf(基本和x)
{
返回!x;
}
模板布尔等式(基准和x、基准和y)
{
返回x==y;
}
主函数调用这些模板函数

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; }
};
int main()
{
    Derived x, y;
    cout << notf(x);
    cout << equalf(x, y);
    return 0;
}
intmain()
{
导出x,y;
cout
Base::operator==(T操作数)
无法接受
Base
参数(因为没有定义转换)

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


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

CRTP通过非虚拟方法提供编译时多态性。虚拟方法提供运行时多态性。其目的是什么在你的例子中,CRTP模式的作用是什么?或者让方法虚拟的目的是什么?@Cheersandhth.-Alf我使用CRTP在基类中使用T类型,因为基类中的运算符==必须采用T类型参数。我认为这就是你试图做的,尽管我仍然不清楚你为什么真的要这么做。