When is C++ covariance the best solution?

后端 未结 6 711
温柔的废话
温柔的废话 2020-12-05 23:00

This question was asked here a few hours ago and made me realise that I have never actually used covariant return types in my own code. For those not sure what covariance is

6条回答
  •  醉梦人生
    2020-12-05 23:47

    I think covariance can be useful when declaring factory methods that return a specific class and not its base class. This article explains this scenario quite well, and includes the following code example:

    class product
    {
        ...
    };
    
    class factory
    {
    public:
        virtual product *create() const = 0;
        ...
    };
    

    class concrete_product : public product
    {
        ...
    };
    
    class concrete_factory : public factory
    {
    public:
        virtual concrete_product *create() const
        {
            return new concrete_product;
        }
        ...
    };
    

提交回复
热议问题