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

标签 c++ c++11

我想要一个集合返回 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/

相关文章:

c++ - 模板特化和别名模板推导区别

c++ - 为什么我的线程不在后台运行?

c++ - 智能指针 std::pair 的元素

c++ - 为什么新对象的成员没有被 std::make_unique 初始化?

c++ - 我可以命名从接口(interface)派生的每个类吗?

c++ - 在C++中的模板类中定义方法

c++ - 你可以在 `std::remove_if` 的容器上使用 `std::unique_ptr` 吗?

c++ - 在 C++11 中绘制 n 个随机值的优雅方法?

c++ - 有没有办法获取在目录中创建(使用类似 fopen() 之类的东西)或删除文件(使用 rm)的进程的 pid?

c++ - 为什么对 operator<< 的显式调用不明确?