遍历模板参数 [英] Iterate through template parameter

查看:92
本文介绍了遍历模板参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个接收模板参数的函数.

I have a function that receives a 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}});
}

是否可以在一个功能中执行此操作?假设容器参数为整数.

Is it possible to do this in one function? Suppose the container argument will be 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}});
}

这篇关于遍历模板参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆