我想要一个集合返回 this
的类,这样我就可以做嵌套集合。但我的问题是子类也会有一些集合,但如果 API 的用户首先调用父类(super class)中的集合,则类型会发生变化,我无法调用子类方法。
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
我该如何解决这个问题?谢谢
最佳答案
我认为这听起来像是... 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!
关于c++ - 如何返回 `set` 方法的子类类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25006675/