c++函数模板编译
c++ function template compilation
我有这个模板打印出集合结构,但似乎函数是预先编译的参数??
如果我只在函数内部执行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, " ")
相关文章:
- 两阶段函数模板编译:第二阶段不是只使用*ADL吗
- 无法编译包含"if constexpr"的函数模板实例化
- variadic函数模板:基于n编译时值在运行时间自动n输入
- 精神语法不会编译:函数模板参数错误?
- 成员函数模板不会在 clang 上编译,但在 GCC 上编译
- 编译类模板成员函数时出错
- 实例化函数模板的编译问题
- 函数模板无法编译
- 使用额外的模板参数编译函数
- 为什么C++函数模板代码无法编译
- 函数模板参数编译错误
- 如何根据模板中的类型编译函数
- 关于函数模板的相同代码块在g++下编译正常,但在VC6下编译错误,原因是什么
- 最Vexing的朋友?朋友化一个专门的免费函数模板会引发编译错误(当重载一个方法时)
- 跨编译单元的相同函数模板实例化的地址
- 编译普通/模板函数的区别,c++
- 函数模板编译错误
- 通过模板化的函函数特化成员函数模板无法编译
- 编译函数模板时出现"expected nested-name-specifier"错误
- 用C++编译函数模板时出错