派生类函数参数作为基类引用导致C2678
Derived class function parameter as base class reference is causing C2678
我创建了派生类,该类派生的是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>
参数(因为没有定义转换)。
很难提出修复方案,因为代码指向许多可能的设计方向。
然而,无论如何,虚拟比较运算符或虚拟赋值的想法通常是不好的,因为它将类型检查转移到了运行时,因此您需要更多的测试和更复杂的代码。
相关文章:
- 将对象数组的引用传递给函数
- 什么时候在C++中返回常量引用是个好主意
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 何时在引用或唯一指针上使用移动语义
- 如何在c++中使用引用实现类似python的行为
- 编译C++时未定义的引用
- Ctypes wstring通过引用传递
- c++r值引用应用于函数指针
- 理解c++中的引用
- C++取消引用指针.为什么会发生变化
- 如何修复此错误:未定义对"距离(浮点数,浮点数,浮点数,浮点数,浮点数)"的引用
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 强制转换为引用类型
- 引用一个已擦除类型(void*)的指针
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 具有默认值的引用获取函数
- 如何使用基类指针引用派生类成员
- 派生类函数参数作为基类引用导致C2678
- 比较未引用的映射迭代器(std::pairs):C2678