-2

How to get the no of elements in a tuple. So that I can do the below.

for(int i=0;i<tuple.count();++i)
    cout << std::get<i>(tuple) << endl;

EDIT: My question is tuple size, not iterate over it's members. That is another subject. So the core point is getting tuple size. Iterating over is extra. So it is not duplicate of the question you mentioned.

prabhakaran
  • 5,126
  • 17
  • 71
  • 107

1 Answers1

4

You can use tuple_size to know size of tuple

int size = tuple_size<decltype(mytuple)>::value; // size of tuple

Update:

In order to use values of tuple it needs to be known at compile time, not at runtime. So you can't use loop directly.

Rather than you can use get<0>(mytuple), get<1>(mytuple), get<2>(mytuple) for each index value.

Faruk Hossain
  • 1,205
  • 5
  • 12
  • But `i` in `std::get(tuple)` is a template parameter. Therefor it needs to be known at compile-time. So you can not iterate through with a `for` loop. –  Aug 22 '19 at 11:57
  • Using index_sequence with fold expression could do the access, see [example here](https://en.cppreference.com/w/cpp/utility/integer_sequence) – Kai Gu Jun 07 '22 at 19:37