复制 - 构造和随后访问任意POD类型 [英] Copy-construct and later access arbitrary POD types

查看:132
本文介绍了复制 - 构造和随后访问任意POD类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在下面的代码中填写 store() launch()方法。捕获问题精神的重要细节是在 main()中声明的对象 foo 不再存在我们调用 launch()的时间。我该如何做?

I'd like to fill in the store() and launch() methods in the below code. The important detail which captures the spirit of the problem is that the object foo declared in main() no longer exists at the time we call launch(). How can I do this?

#include <cstdio>
#include <cstring>
#include <type_traits>

template<typename T, typename U=
  typename std::enable_if<std::is_trivially_copyable<T>::value,T>::type>
struct Launchable {
  void launch() { /* some code here */ }

  T t;
  // other members as needed to support DelayedLauncher 
};

class DelayedLauncher {
public:
  template<typename T>
    void store(const Launchable<T>& t) {
      // copy-construct/memcpy t into some storage
    }

  void launch() const {
    // call t.launch(), where t is (a copy of) the last value passed into store()
  }

  // other members as needed
};

int main() {
  DelayedLauncher launcher;
  {
    Launchable<int> foo;
    launcher.store(foo);
  }
  launcher.launch();  // calls foo.launch()
  return 0;
}

注意,如果我们只有一组固定的N类型, code> store(),我们可以通过声明N 可启动< T> 字段和N非模板 store()方法,每个类型一个,以及一个枚举字段,其值在 switch code> launch()方法。但是我正在寻找 DelayedLauncher 的实现,不需要修改,因为添加了更多的可启动类型。 p>

Note that if we only had a fixed set of N types to pass into store(), we could achieve the desired functionality by declaring N Launchable<T> fields and N non-template store() methods, one for each type, along with an enum field whose value is use in a switch statement in the launch() method. But I'm looking for an implementation of DelayedLauncher that will not need modification as more Launchable types are added.

推荐答案

使用 std :: function

class DelayedLauncher {
public:
  template<typename T>
    void store(const Launchable<T>& t) {
      f = [t]() {t.launch();};
    }

  void launch() const { f(); }

 private:
     std::function<void()> f;
};

这篇关于复制 - 构造和随后访问任意POD类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆