Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the stdlib provide a type list?

In modern C++, does the standard library provide a type list template?

int main() {
    using int_types = type_list<int,long,short,char>;
    std::cout << length<int_types>::value << ' '
              << typeid(element<2,int_types>::type).name();
}

Note that int_types does not store any values (as std::tuple does). It's merely a list of types.

like image 968
sbi Avatar asked Jun 16 '19 11:06

sbi


2 Answers

It seems to me that, in modern C++ standard library, nearest what you want is std::tuple.

If the problem is that std::tuple store values of the listed types (so, I suppose, can be a problem instantiate an object of that type) it's easy write a instantiable object that wraps a std::tuple using without instantiate the std::tuple itself.

I mean... given a wrapper like this

template <typename ... Ts>
struct wrapTuple
 {
   using type = std::tuple<Ts...>;

   template <std::size_t N>
   using element = std::tuple_element_t<N, type>;

   static constexpr auto length { std::tuple_size_v<type> };
 };

you can write the following lines without instantiate the wrapper

   using int_types = wrapTuple<int, long, short, char>;

   std::cout << int_types::length << ' '
      << typeid(int_types::element<2u>).name() << std::endl;

but you can also instantiate it without instantiate the std::tuple

   int_types it;

   std::cout << it.length << ' '
      << typeid(decltype(it)::element<2u>).name() << std::endl;
like image 98
max66 Avatar answered Oct 16 '22 09:10

max66


Use std::tuple type but don't instantiate it:

#include <iostream>
#include <tuple>

int main()
{
    using int_types = std::tuple<int, long, short, char>;
    std::cout << std::tuple_size_v<int_types> << ' '
        << typeid(std::tuple_element_t<2, int_types>).name();
}

MSVC output:

4 short

GCC output:

4 s

Clang output:

4 s
like image 1
Ayxan Haqverdili Avatar answered Oct 16 '22 09:10

Ayxan Haqverdili