c++函数模板编译

c++ function template compilation

本文关键字:编译 函数模板 c++      更新时间:2023-10-16

我有这个模板打印出集合结构,但似乎函数是预先编译的参数??

如果我只在函数内部执行print语句,那么该类型的If else情况确实有效,但是,如果我为每种情况添加不同的实现,它会针对每种情况测试参数。

在程序运行之前给出一个错误(我认为)。即使我把断点放在程序的开始处,我也不能遍历代码。

有人能给我上一堂课吗?如何绕过这个问题呢?谢谢你!很感激。
  template <typename T>
  void print(T& collection)
  {
     string type = typeid(T).name();
     if(type.find("map") != string::npos){
        for(auto const& item : collection){
           std::cout << item.first << " " << item.second << endl;
        }
     }
     else {
        for(auto const& item : collection){
           std::cout << item << std::endl;
        }
     }
  }

如果我用map调用函数,下面是错误:

 error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'const std::__1::pair<const std::__1::basic_string<char>, int>')
                    std::cout << item << std::endl;
类似地,如果与数组一起调用:
 error: member reference base type 'const int' is not a structure or union
                    std::cout << item.first << " " << item.second << endl;

当模板参数不支持您想要执行的操作时,使用运行时检查来执行不同的代码行是有问题的。

你需要的是:

template <typename T>
void print(T& collection)
{
   for ( auto const& item : collection )
   {
      std::cout << item << endl;
   }
}

为了能够对std::map使用上述功能,为std::pair提供operator<<()过载。

template <typename T1, typename T2>
std::ostream& operator<<(std::ostream& out, std::pair<T1, T2> const& p)
{
   return out << p.first << " " << p.second;
}

您可以使用下面的简单宏缩短打印函数。

#define dbg_cnt(cnt) copy(cnt.begin(), cnt.end(), ostream_iterator<decltype(cnt)>(cout, " ")