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 astd::vector
, serialize each item usingserialize<Item>
withT=std::vector<Item>
.If
T
is astd::map
, serialize each key and value separately usingserialize<K>
andserialize<V>
withT=std::map<K,V>
.If
T
is astd::tuple
, serialize each component usingserialize<Ci>
with i in {0, n-1} where n is the size of the tuple andCi
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.