0

I am reading the book C++ primier, the tuple part. I had a problem when I finished a test program. Here's the 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);

    for (int  i = 0; i <tuple_size<decltype(tuple1)>::value; i++)
    {
        cout << get<i>(tuple1) << endl;
    }
}

But the get<i> function didn't work as i is non-const. How can I make i const? Or is there easier way to get the get<...> function working?

Thank you @R Sahu for your answer and @Praetorian for linking to the duplicate question. Now I know that there's not an easy way to get over the problem.

But now I wonder why there isn't a easy way to do this in c++11?Thanks.

  • This one is similar: http://stackoverflow.com/questions/30531017/working-around-the-static-type-property-of-c/30531182#30531182 – marom Jun 03 '15 at 19:45
  • short answer why it isn't easy to do this in c++: Simply put, c++ doesn't have [introspection](http://en.wikipedia.org/wiki/Type_introspection) (you can argue it has some limited introspection). – bolov Jun 04 '15 at 14:10

1 Answers1

2

You can use templates to simulate a 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 to be 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
R Sahu
  • 204,454
  • 14
  • 159
  • 270