c – 抽象类的逆变

前端之家收集整理的这篇文章主要介绍了c – 抽象类的逆变前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在C上创建一个很好的接口,每个实现都需要在其上定义添加.

我想做这样的事情:

@H_403_4@class A{ ... virtual A& operator+(const A& other) =0; ... } // this is my interface or abstract class. class B : A{ ... B& operator+(const B& other); ... } // this is the kind of implementation i would like. a B element can be added by another B element only ! At least this the constraint I am aiming at.

因为c不接受逆变,我的功能B&运算符(const B& other)不实现虚拟A&运算符(const A& other).有没有什么棘手的(但有点干净……)方法呢?

解决方法

@H_403_4@template<class Y> class A { virtual Y& operator+=(const Y& other) = 0; }; class B : A<B> { // must implement B& operator+=(const B& other) else B is abstract };

是一种方式.这个习惯用法在实施政策时很常见.见http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern

猜你在找的C&C++相关文章