c++ - 抽象类的逆变

标签 c++ abstract-class contravariance function-parameter

我想在 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/

相关文章:

c++ - 如果满足条件,如何退出 Qt 脚本?

c++ - 模板继承和抽象类

c++ - 为什么未验证模板模板参数中的概念?

c++ - 带有抽象类的列表与 vector

.net - API 设计中的异步抽象方法和派生类

c#-4.0 - 我可以有一个既是协变又是逆变的类型,即完全可替换/可更改的子类型和 super 类型吗?

Kotlin 泛型函数和逆变

c++ - 除了使用 new 之外,还有什么会导致内存泄漏? (c++)

c++ - 如何将可变参数模板成员函数的参数存储到 vector 中?

c++ - 如何在网格上找到从 A 到 B 的最短路径?