【发布时间】:2014-08-13 06:23:50
【问题描述】:
我想专门为矢量和地图之类的容器创建一个函数模板。对于矢量,我可以像下面那样做,但我不知道我怎样才能有一个专门的函数版本,只用于像容器这样的地图。
#include <iostream>
#include <vector>
#include <map>
using namespace std;
template<typename Iterator>
void print(Iterator begin, Iterator end)
{
while (begin != end)
{
cout << *begin << endl; // compiler error for map like containers
++begin;
}
}
int main()
{
vector<int> noVec = { 1, 2, 3 };
print(noVec.begin(), noVec.end());
map<int, int> nosMap;
nosMap[0] = 1;
nosMap[1] = 2;
nosMap[3] = 3;
print(nosMap.begin(), nosMap.end());
return 0;
}
This 问题类似,但它建议在我不想做的向量中使用pair。我知道可以通过 SFINAE 完成专业化,但不知道要检查什么条件。如果我可以使用 C++ 11 type_traits 实现这一点,那就太好了。
【问题讨论】: