我想在 C++ 上创建一个漂亮的接口(interface),每个实现都需要在其自身上定义附加项。
我想做这样的事情:
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& operator+(const B& other)
没有实现 virtual A& operator+(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
关于c++ - 抽象类的逆变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26846868/