Iterate through template parameter

只谈情不闲聊 提交于 2020-03-05 02:07:31

问题


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.


回答1:


One example:

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}});
}



回答2:


This should work for your case. Note that I'm using a trait as implemented here in this amazing solution by @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)
       {...}
    }
}



回答3:


With is_iterable traits, you might do:

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


来源:https://stackoverflow.com/questions/60298529/iterate-through-template-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!