从 std::future::get 获取派生值类型

时间:2021-07-23 13:34:32

标签: c++ c++11 inheritance polymorphism future

我想从类方法返回一个 std::futurestd::future 的值类型取决于具体类。我想知道如何在不知道使用哪个具体类的先验情况下 get() std::future 的值。

这是一个简化的例子,它只使用了一个派生的 ValueAAppA 类。在我的实际问题中,我有多个类(AppBValueB 等)从相应的基类继承。我想避免使用模板化的 App 类,因为在现实世界中,大多数方法不依赖于 ValueBase 的类型。

#include <future>
#include <memory>

class ValueBase
{
public:
  virtual int value() const = 0;
};

class ValueA : public ValueBase
{
public:
  int value() const override
  {
    return 0;
  }
};


class AppBase
{
public:
  virtual std::future<const ValueBase&> get() = 0;
};

class AppA : public AppBase
{
public:
  std::future<const ValueBase&> get() override
  {
    std::promise<const ValueBase&> promise;
    promise.set_value(value_);
    return promise.get_future();
  }

private:
  ValueA value_;
};


int main()
{
  std::unique_ptr<AppBase> app = std::make_unique<AppA>();
  auto future = app->get();

  // If I know that app uses ValueA, I can cast it
  const auto valueA = dynamic_cast<const ValueA&>(future.get());

  // How to get the value if the type/concrete class is not known?
  // The following line does not compile with
  // Variable type 'const ValueBase' is an abstract class
  const auto value = future.get();
}

0 个答案:

没有答案
相关问题