获取元组类型作为模板参数包

问题描述 投票:0回答:0

我有一个名为

serialize
的函数模板,它采用这样的模板参数:

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

我有不同的用例

serialize
,它们取决于
T

  • 一般情况下,

    serialize
    应该抛出异常。

  • 如果

    T
    std::vector
    ,使用
    serialize<Item>
    T=std::vector<Item>
    序列化每个项目。

  • 如果

    T
    std::map
    ,使用
    serialize<K>
    serialize<V>
    T=std::map<K,V>
    分别序列化每个键和值。

  • 如果

    T
    是一个
    std::tuple
    ,使用
    serialize<Ci>
    序列化每个组件,其中 i 在 {0, n-1} 中,其中 n 是元组的大小,
    Ci
    是位置 i 处组件的类型.

我想我可以使用

std::enable_if
is_specialization
来区分这些情况,这就是为什么我这样写它们:

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>*/ }

当然,这里是

is_specialization
的实现:看这里

您会注意到我没有为

std::tuple
-case 提供实现,这是因为我不知道如何编写那个。我的第一个冲动是按照以下方式做一些事情:

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

但是我怎么得到

Ci
?你知道如何正确编写
std::tuple
-case吗?

我试图用

???
替换
std::enable_if
以确定
Tuple
是否是
std::tuple
,但与
std::vector
std::map
的情况不同,我无法获得包含元组类型的参数包来自元组类本身......或者我可以吗?我真的不知道。

提前致谢!

c++14
© www.soinside.com 2019 - 2024. All rights reserved.