我想在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
原文地址:https://www.jb51.cc/c/113965.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。