|
Boost : |
Subject: [boost] [optional] How to use optional to lazy construct obj?
From: Mostafa (mostafa_working_away_at_[hidden])
Date: 2015-07-01 17:17:34
I'm interested in doing something along the lines of:
lazy_adaptor<obj_type> lz(arg1, arg2, arg3, ...)
where then lz.construct() then constructs an object of obj_type with ctor
of arguments "arg1, arg2, arg3, ...". So far I have the following: (Am I
on the right track?)
#include <utility>
#include <tuple>
#include <string>
#include <boost/optional/optional.hpp>
template <typename... Args>
struct ctor_forwarder;
template <typename... Args>
ctor_forwarder<Args...>
make_ctor_forwarder(Args&&... args)
{
// Note: The "Args..." template parameter to ctor_forwarder determines
how
// the caller's arguments are temporarily stored. If it's an rvalue,
it's
// temporarily stored by value, else it's temporary stored by
reference.
return
ctor_forwarder<Args...>(std::forward<Args>(args)...);
}
template <typename... Args>
struct ctor_forwarder
{
//TODO: make ctor private.
template <typename... A>
explicit ctor_forwarder(A&&... args)
: m_args( ::std::forward<A>(args)... )
{}
/*
template <typename Callable>
auto forward_to(Callable && caller) ->
decltype( caller(::std::forward<Args>(m_args)...) )
{
return caller(::std::forward<Args>(m_args)...);
}
*/
template <typename T>
void forward_to(::boost::optional<T> & obj)
{
obj.emplace(::std::forward<Args>(m_args)...);
}
private:
typedef ::std::tuple<Args...> args_t;
private:
args_t m_args;
};
template <typename Obj, typename... Args>
struct lazy_adaptor
{
Obj on_enter()
{
m_args_forwarder.forward_to(m_obj);
}
private:
::boost::optional<Obj> m_obj;
ctor_forwarder<Args...> m_args_forwarder;
};
template <typename Obj, typename... Args>
lazy_adaptor<Obj, Args...> make_lazy_adaptor(Args&&... args)
{
return lazy_adaptor<Obj, Args...>();
}
struct Sample1
{
Sample1(int num, std::string str) {}
};
int main()
{
auto df = make_ctor_forwarder(10, "Ten");
//ctor_forwarder<int, std::string> df(10, "Ten");
auto lazy_ctor = make_lazy_adaptor<Sample1>(10, "Ten");
return 0;
}
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk