在没有参数的变异模板中迭代
iterate in variadic templates without parameters
我有一个数据对象"值",该值可以包含不同类型的值(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
中的技术。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 实现一个在集合上迭代的模板函数
- 对于set上的循环-获取next元素迭代器
- 在向量内的向量上迭代
- 为什么output_editor Concept不需要output_e迭代器标记
- TSP递归解的迭代形式
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- 迭代器在递增和递减时是否保证会变异?
- 在没有参数的变异模板中迭代