我想要一个类返回的类,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
Run Code Online (Sandbox Code Playgroud)
我怎样才能解决这个问题?谢谢
我认为这听起来像是一份工作... 奇怪的重复模板模式(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;
}
};
Run Code Online (Sandbox Code Playgroud)
SubA* a = new SubA();
a->setValue(1)->setOtherValue(12); // Works!
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
403 次 |
| 最近记录: |