cogle
cogle

Reputation: 1079

Tuple size default constructor and its conversion to std::size_t

In the code below I am wondering how exactly std::tuple_size<T>{} and std::tuple_size<T>() return the size of the tuple. When looking at the docs for using this call, it seems that I should either have to use the () operator or the static ::value member variable in order to get the tuple size. However, when running this code it compiles and produces the correct output, how is tuple_size returning the value from the constructor?

#include <iostream>
#include <tuple>

template <class T>
void test(T)
{
    //std::make_index_sequence<std::tuple_size<T>{}>{} Seen used like this spurned my ?
    std::cout << std::tuple_size<T>{} << '\n';
    std::cout << std::tuple_size<T>() << '\n';
    std::cout << std::tuple_size<T>()() << '\n';
    std::cout << std::tuple_size<T>::value << '\n';
}

int main()
{
    test(std::make_tuple(1, 2, 3.14));
}

Upvotes: 1

Views: 164

Answers (1)

Red.Wave
Red.Wave

Reputation: 4226

http://en.cppreference.com/w/cpp/utility/tuple/tuple_size

Says:

Member constants

value

[static]

sizeof...(Types)  (public static member constant)

Member functions

operator std::size_t

converts the object to std::size_t, returns value  (public member function)

operator()

(C++14)

returns value  (public member function)

So no wonder. 1st & 2nd form use conversion operator. 3rd form explicitly calls function call operator. 4th form uses static member. This is an exceptionally convenient std utility. No other std tool has as many convenience functions.

Upvotes: 1

Related Questions