我有一个数据对象“值”,它可以包含不同类型的值(int、std::string、bool 等)。我想使用可变参数模板在元组中反序列化它:
tuple<int, std::string, bool> tuple = data.Deserialize<int, std::string, bool>();
在我的 Deserialize 方法中,我想迭代类型(这里是 int、std::string 和 bool)以在每次调用另一个知道如何获取数据的 Deserialize 方法时调用。
是否可以 ?
是否可以 ?
是的。
这是一个 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` ...
});
这是一个 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{});
}
如果不需要迭代类型序列的通用方法,则可以for_types
直接在Deserialize
定义中应用内部提供的技术。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句