c++ - Constructor arguments from tuple -
suppose have template parametrized class type , number of argument types. set of arguments matching these types stored in tuple. how can 1 pass these constructor of class type?
in c++11 code:
template<typename t, typename... args> struct foo { tuple<args...> args; t gen() { homecoming t(get<0>(args), get<1>(args), ...); } };
how can ...
in constructor phone call filled without fixing length?
i guess come complicated mechanism of recursive template calls this, can't believe i'm first want this, guess there ready-to-use solutions out there, perhaps in standard libraries.
you need template meta-programming machinery accomplish that.
the easiest way realize argument dispatch exploit pack expansion on expressions contain packed compile-time sequence of integers. template machinery needed build such sequence (also see remark @ end of reply more info on proposal standardize such sequence).
supposing have class (template) index_range
encapsulates compile-time range of integers [m, n) , class (template) index_list
encapsulates compile-time list of integers, how utilize them:
template<typename t, typename... args> struct foo { tuple<args...> args; // allows deducing index list argument pack template<size_t... is> t gen(index_list<is...> const&) { homecoming t(get<is>(args)...); // core of mechanism } t gen() { homecoming gen( index_range<0, sizeof...(args)>() // builds index list ); } };
and here possible implementation of index_range
, index_list
:
//=============================================================================== // meta-functions creating index lists // construction encapsulates index lists template <size_t... is> struct index_list { }; // collects internal details generating index ranges [min, max) namespace detail { // declare primary template index range builder template <size_t min, size_t n, size_t... is> struct range_builder; // base of operations step template <size_t min, size_t... is> struct range_builder<min, min, is...> { typedef index_list<is...> type; }; // induction step template <size_t min, size_t n, size_t... is> struct range_builder : public range_builder<min, n - 1, n - 1, is...> { }; } // meta-function returns [min, max) index range template<unsigned min, unsigned max> using index_range = typename detail::range_builder<min, max>::type;
also notice, interesting proposal jonathan wakely exists standardize int_seq
class template, similar called index_list
here.
c++ templates c++11 constructor stdtuple
No comments:
Post a Comment