遍历模板参数
Iterate through template parameter
我有一个接收模板参数的函数。
template<class Container>
void function(const Container& object)
{
//here i want to iterate through object and print them
}
int main()
{
function(std::vector<int>{1,3,6,7});
function(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}
有可能在一个函数中执行此操作吗?假设容器参数是integer。
一个例子:
template<class T>
void print(T const& object) {
std::cout << object;
}
template<class... Args>
void print(std::vector<Args...> const& container) {
for(auto const& element : container) {
print(element);
std::cout << ' ';
}
std::cout << 'n';
}
int main() {
print(std::vector<int>{1,3,6,7});
print(std::vector<std::vector<int>>{{1,2,3},{2,5,7}});
}
这应该适用于您的案例。请注意,我使用的是@Jarod42在这个令人惊叹的解决方案中实现的特性https://stackoverflow.com/a/29634934/8192043.
template<template<typename ...> typename C, typename D, typename ... Others>
void function(const C<D, Others...> &object)
{
if constexpr(is_iterable<D>::value)
{
for(const auto& v : object)
{
for (const auto& w : v)
{...}
}
}
else
{
for (const auto& w : object)
{...}
}
}
使用is_iterable
特性,您可以执行以下操作:
template<typename Container>
void function(const Container& object)
{
if constexpr(is_iterable<std::decay_t<*object.begin()>>::value)
{
for(const auto& v : object)
{
function(v); // recursive call
}
}
else
{
for (const auto& w : object)
{
// ...
}
}
}
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 如何在可变参数模板函数中遍历可变参数元组?
- C++类对象 - 遍历基于参数的对象
- 遍历地图并将该对用作参考参数 C++11
- 遍历模板参数包,没有争论的专业化的作用是什么?
- 编写一个通用遍历函数,允许灵活地处理具有不同参数的多个函数
- 如何遍历可变参数模板以填充 POD 数组
- 具有多个参数的树遍历
- C++二进制树遍历和函数指针参数
- 序遍历的二叉搜索树,没有节点指针作为参数
- 在c++中循环遍历函数的所有参数
- For循环遍历模板参数/类型
- 我们是否可以创建一个类似scanf的函数,当所有参数都填充时返回true,否则返回false,而不循环遍历所有变量?