templates - C++ std::get equivalent with run-time arguments -
one cannot directly use std::get
run-time arguments:
template<typename tuple> void get(size_t i, tuple const& t) { using std::get; std::cout<<get<i>(t)<<std::endl; //error: 'i' not constant expression } int main() { std::tuple<int,double> t; get(1,t); }
however, 1 can manually map run-time compile-time information:
template<typename tuple> void get_impl(size_t i, tuple const& t, typename std::tuple_size<tuple>::type) {} template<size_t n, typename tuple, typename = std::enable_if_t<std::tuple_size<tuple>::value != n> > void get_impl(size_t i, tuple const& t, std::integral_constant<size_t, n>) { if(i==n) { std::cout<<std::get<n>(t)<<std::endl; } else { get_impl(i, t, std::integral_constant<size_t, n+1>()); } } template<typename tuple> void get(size_t i, tuple const& t) { get_impl(i, t, std::integral_constant<size_t, 0>()); }
which seems rather conventient me (demo).
with this, 1 can apply arbitrary functions (which accept tuple members) tuple-element chosen @ run-time.
is there reason why or similar not in standard library? missing relevant here hinders proper application?
Comments
Post a Comment