c++中模板函数接收的迭代对象

c++ iterating objects taken in by template function

本文关键字:迭代 对象 函数 c++      更新时间:2023-10-16

我有两段看起来很相似的代码,我想利用模板来防止复制代码。

if(!myVector.empty()) {
    for(auto& i : myVector)
    {
        std::cout << i << std::endl;
        //some other code that is similar to below
   }
}
if(!myUnorederedMap.empty()) {
    for(auto i : myUnorderedMap)
    {
        std::cout << i.second << std::endl;
        //some other code that is similar to top
    }
}

当我必须在map上调用。second而不是vector时,如何为迭代器编写函数模板?

template <typename T>
T const& getValue(T const& t)
{
   return t;
}
template <typename T, typename U>
U const& getValue(std::pair<T, U> const& p)
{
   return p.second;
}

template <typename Container>
void foo(Container const& container)
{
   if(!container.empty()) {
      for(const auto& i : container)
      {
        std::cout << getValue(i) << std::endl;
      }
   }
}

虽然,行if(!container.empty())似乎没有任何用途。你也可以这样写:

template <typename Container>
void foo(Container const& container)
{
   for(const auto& i : container)
   {
     std::cout << getValue(i) << std::endl;
   }
}