如何返回`set`方法的子类类型?

时间:2014-07-29 00:56:01

标签: c++ c++11

我想要一个类,其中集合返回this,所以我可以做嵌套集。但我的问题是子类也有一些集合,但如果API的用户首先调用超类中的一个集合,那么类型会发生变化而我无法调用子类方法。

class SuperA {
 public:
  SuperA* setValue(int x) {
    return this;
  }
}

class SubA : public SuperA {
 public:
  SubA* setOtherValue(int y) {
    return this;
  }
}

SubA* a = new SubA();
a->setValue(1)->setOtherValue(12); // Compile error

我该如何解决这个问题?感谢

2 个答案:

答案 0 :(得分:5)

我认为这听起来像...... Curiously Recurring Template Pattern (CRTP)的作业!

template <typename Child>
class SuperA
{
public:
    Child* setValue(int x)
    {
        //...
        return static_cast<Child*>(this);
    }
};

class SubA : public SuperA<SubA>
{
public:
    SubA* setOtherValue(int y)
    {
        //...
        return this;
    }
};

SubA* a = new SubA();
a->setValue(1)->setOtherValue(12); // Works!

答案 1 :(得分:3)

此搜索词是协变返回类型

您必须在子类中重新定义setValue:例如

class SubA : public SuperA
{
public:
    SubA *setValue(int x) { SuperA::setValue(x); return this; }
    // other methods...
};

在此示例中,setValue是非虚拟的,SubA::setValue隐藏基类版本,它不会覆盖。

如果函数是虚函数,那么只要子类版本的返回类型是指向超类的版本的返回类型的指针或引用,这仍然有效,并且会发生重写。 / p>

相关问题