我有2个重载函数说 - func1和func2 -
Func1是 -
template<typename T1, typename T2> bool AreIdentical(const std::pair<T1, T2>
&lhs, const std::pair<T1, T2> &rhs)
{
//some code
}
Func2是 -
template<typename T> bool AreIdentical(typename std::map<int,
std::vector<T>>::iterator itOrig,
typename std::map<int, std::vector<T>>::iterator itNew)
{
//some code
}
我试图以下面的方式调用函数 AreIdentical -
int main()
{
std::map<int, std::vector<int>> orgitem;
std::map<int, std::vector<int>> newitem;
newitem[0];
orgitem[0];
AreIdentical(*orgitem.begin(), *newitem.begin());
return 0;
}
现在,有趣的是,我的原创和 newitem 属于地图类型,但始终 Func1 正在获取调用哪个采用参数对类型而不是 Func2 。
有没有人知道为什么会这样?
答案 0 :(得分:2)
orgitem.begin()
是一个迭代器。但是*orgitem.begin()
是迭代器指向的对象,它是std::pair<const int, std::vector<int>>
。
如果你有
AreIdentical(orgitem.begin(), newitem.begin());
没有解除引用*
运算符,无法调用pair
重载。
但事实上它也不起作用,因为在你的第二次重载中,参数T
不在可推导的上下文中。调用它的唯一方法是:
AreIdentical<int>(orgitem.begin(), newitem.begin());
您可以通过更改迭代器重载来“修复”它,只需接受其值类型包含成员first
和second
的任何迭代器:
template <typename Iter>
auto AreIdentical(Iter itOrig, Iter itNew)
-> decltype((*itOrig).first, (*itOrig).second, bool{});