Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get types of tuple as template parameter pack

Tags:

c++

c++14

I have a function-template called serialize which takes a template parameter like this:

template <typename T>
std::string serialize(T const & t);

I have different use-cases for serialize and they depend on T.

  • In general, serialize shall just throw an exception.

  • If T is a std::vector, serialize each item using serialize<Item> with T=std::vector<Item>.

  • If T is a std::map, serialize each key and value separately using serialize<K> and serialize<V> with T=std::map<K,V>.

  • If T is a std::tuple, serialize each component using serialize<Ci> with i in {0, n-1} where n is the size of the tuple and Ci is the type of the component at position i.

I figured I could use std::enable_if with is_specialization to differentiate those cases, which is why I wrote them like this:

template <typename T>
std::string serialize(T const & t) { throw std::exception(); }

template <typename TVec,
          typename T = std::enable_if<is_specialization<TVec, std::vector>, TVec::value_type>::type>
std::string serialize(TVec const & tvec) { /*Something with serialize<Item>*/ }

template <typename KVMap,
          typename K = std::enable_if<is_specialization<TMap, std::map>, KVMap::key_type>::type,
          typename V = std::enable_if<is_specialization<TMap, std::map>, KVMap::mapped_type>::type>
std::string serialize(KVMap const & kvmap) { /*Something with serialize<K> and serialize<V>*/ }

And of course, here's the implementation of is_specialization : See here

You'll notice I didn't provide an implementation for the std::tuple-case, which is because I don't know how to write that one. My first impulse was to do something along the lines of:

template <typename Tuple,
          ???>
std::string serialize(Tuple const & tup) { /*Something with serialize<Ci> for different Ci*/ }

But how do I get Ci? Do you have an idea how to correctly write the std::tuple-case?

I tried to replace ??? with an std::enable_if to find out whether Tuple is a std::tuple, but unlike the cases with std::vector and std::map I cannot get a parameter-pack containing the tuples' types from the tuple-class itself... or can I? I really don't know.

like image 469
ChaosNe0 Avatar asked Dec 16 '25 12:12

ChaosNe0


1 Answers

Why not just

template <typename... Ts>
std::string serialize(const std::tuple<Ts...>&) { /* ... */ }

?

like image 55
Vittorio Romeo Avatar answered Dec 19 '25 02:12

Vittorio Romeo