在没有参数的可变参数模板中迭代

时间:2017-03-13 13:41:56

标签: c++ variadic-templates

我有一个数据对象"值"它可以包含不同类型的值(int,std :: string,bool等)。 我想使用variadic模板在元组中反序列化它:

entityRepo.save(EntityList);

在我的Deserialize方法中,我想迭代类型(这里是int,std :: string和bool),每次调用另一个知道如何获取数据的Deserialize方法。

有可能吗?

1 个答案:

答案 0 :(得分:3)

  

有可能吗?

是。

这是一个C ++ 17解决方案:

template <typename T>
struct type_wrapper { using type = T; };

template <typename... Ts, typename TF>
void for_types(TF&& f)
{
    (f(type_wrapper<Ts>{}), ...);
}

用法:

for_types<int, std::string, bool>([](auto t)
{
    using t_type = typename decltype(t)::type;
    // logic for type `t_type` ...
});

live wandbox example

这是一个C ++ 11解决方案:

template <typename TF, typename... Ts>
void for_each_arg(TF&& f, Ts&&... xs)
{
    using swallow = int[];
    return (void)swallow{(f(std::forward<Ts>(xs)), 0)...};
}

template <typename T>
struct type_wrapper { using type = T; };

template <typename... Ts, typename TF>
void for_types(TF&& f)
{
    for_each_arg(std::forward<TF>(f), type_wrapper<Ts>{}...);
}

用法:

struct body
{
    template <typename T>
    void operator()(type_wrapper<T>) const
    {
        // logic for type `T` ...
    }
};

int main()
{
    for_types<int, float, bool>(body{});
}

live wandbox example

如果您不需要对一系列类型进行迭代的一般方法,则可以直接在for_types定义中应用Deserialize中提供的技术。