I’m wondering if something like
template <typename T>
class LazyLoaded
{
mutable char mem[sizeof T]; //First item in the class to keep alignment issues at bay
const std::function<void (T&)> initializer;
mutable bool loaded;
public:
LazyLoaded() : loaded(false)
{
initializer = [] (T&) {};
}
LazyLoaded(const std::function<void (T&)>& init) : initializer(init), loaded(false)
{
}
T& Get()
{
if (!loaded)
{
new (static_cast<void *>(&mem)) T();
initializer(*static_cast<T*>(&mem));
loaded = true;
}
return *static_cast<T*>(&mem);
}
~LazyLoaded()
{
if (loaded)
{
static_cast<T*>(&mem)->~T();
}
}
};
is possible or makes sense to do. (I think there are issues with this code, but hey, I threw it together in 10 minutes, so….)
It’s called
boost::optional. This should provide almost all the necessary functionality.