【问题标题】:OVerloaded function calling issue超载函数调用问题
【发布时间】:2018-05-09 04:34:16
【问题描述】:

我有 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;
}

现在,有趣的是,我的 origitemnewitemma​​p 类型但总是 Func1调用它接受参数 pair 类型而不是 Func2

有人知道为什么会这样吗?

【问题讨论】:

    标签: c++ vector overloading


    【解决方案1】:

    orgitem.begin() 是一个迭代器。但是*orgitem.begin()是迭代器指向的对象,也就是std::pair&lt;const int, std::vector&lt;int&gt;&gt;

    如果你有

    AreIdentical(orgitem.begin(), newitem.begin());
    

    如果没有取消引用 * 运算符,将无法调用 pair 重载。

    但实际上它也不起作用,因为在您的第二次重载中,参数T 不在可推断的上下文中。唯一的调用方式是:

    AreIdentical<int>(orgitem.begin(), newitem.begin());
    

    您可以通过将迭代器重载更改为仅接受其值类型具有成员 firstsecond 的任何迭代器来“修复”此问题:

    template <typename Iter>
    auto AreIdentical(Iter itOrig, Iter itNew)
        -> decltype((*itOrig).first, (*itOrig).second, bool{});
    

    【讨论】:

    • 非常感谢@aschelper!你说的对!成功了!
    • 我只是不小心使用了 AreIdentical(orgitem.begin(), newitem.begin());而不是 AreIdentical(*orgitem.begin(), *newitem.begin());实施您建议的更改后,我仍然面临同样的问题。
    • @Md.ParwezAkhtar 对我来说没问题:coliru.stacked-crooked.com/a/aa27336e28021651
    • 您将 AreIdentical 称为 - AreIdentical(orgitem.begin(), newitem.begin());我想调用 - AreIdentical(*orgitem.begin(), *newitem.begin());有没有可能修改我上面提到的满足调用的重载方法?
    • @Md.ParwezAkhtar 好吧,*orgitem.begin() 是一个pair,所以这会调用你的pair 过载。没有从容器元素返回到它的迭代器的好方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 2018-05-24
    • 2011-10-25
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多