遍历模板参数

Iterate through template parameter

本文关键字:参数 遍历      更新时间:2023-10-16

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

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)
{
// ...
}
}
}