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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…