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

iterate in variadic templates without parameters

本文关键字:迭代 变异 参数      更新时间:2023-10-16

我有一个数据对象"值",该值可以包含不同类型的值(int,std :: string,bool等)。我想使用variadic模板在元组中对其进行测试:

tuple<int, std::string, bool> tuple = data.Deserialize<int, std::string, bool>();

在我的避免方法中,我想迭代类型(此处int,std :: string and bool),每次都会致电另一个知道如何获取数据的供应方法。

可能吗?

可能吗?

是。


这是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示例


这是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示例


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