c++11 - How can I add const to get<>(t) function of tuple in C++ 11? -


this question has answer here:

i reading book c++ primier, tuple part. had problem when finished test program. here's code:

#include <tuple> #include <iostream>  using namespace std;  tuple<int, bool, double> tuple1;  int main() {     tuple1 = make_tuple<int, bool, double>(1,true,3.3);      (int  = 0; <tuple_size<decltype(tuple1)>::value; i++)     {         cout << get<i>(tuple1) << endl;     } } 

but get<i> function didn't work i non-const. how can make i const? or there easier way get<...> function working?

thank @r sahu answer , @praetorian linking duplicate question. know there's not easy way on problem.

but wonder why there isn't easy way in c++11?thanks.

you can use templates simulate for loop.

#include <iostream> #include <tuple>  template <size_t n> struct printer {    template <typename ... args>    static void print(std::tuple<args ...> const& tuple)    {       printer<n-1>::print(tuple);       std::cout << std::get<n-1>(tuple) << std::endl;    } };  // terminating specialization. template <> struct printer<0> {    template <typename ... args>    static void print(std::tuple<args ...> const& tuple)    {       // nothing done here.    } };  template <typename ... args> void printtuple(std::tuple<args ...> const& tuple) {    printer<std::tuple_size<std::tuple<args ...>>::value>::print(tuple); }  int main() {    std::tuple<int, bool, double> tuple1;    tuple1 = std::make_tuple<int, bool, double>(1,true,3.3);     printtuple(tuple1); } 

output:

1 1 3.3 

Comments

Popular posts from this blog

javascript - Bootstrap Popover: iOS Safari strange behaviour -

Magento/PHP - Get phones on all members in a customer group -

session - Logging Out Using PHP -