Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

c++ - Copy-construct and later access arbitrary POD types

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;
}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

using 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;
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...