我想在C上创建一个很好的接口,每个实现都需要在其上定义添加.
我想做这样的事情:
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).有没有什么棘手的(但有点干净……)方法呢?
解决方法
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