代码之家  ›  专栏  ›  技术社区  ›  Hasan Emrah Süngü

存在引用和值重载时函数调用不明确

  •  2
  • Hasan Emrah Süngü  · 技术社区  · 6 年前

    我有以下课程:

    template<typename T>
    class List {
    
        void Add(T& item) {//GOOD STUFF}
        void Add(T item) {//More STUFF}
        void Remove(T item) {//STUFF}
    };
    

    我正试着用它如下

    List<MyClass> list;
    MyClass obj;
    list.Add(obj); //Here the compiler gets angry :((
    

    关于这个问题,我已经找到了下面三个这样的问题,但是我仍然不能调用其中任何一个方法。
    Ambiguous call with overloaded r-value reference function
    function call ambiguity with pointer, reference and constant reference parameter
    Ambiguous Reference/Value Versions of Functions

    1 回复  |  直到 6 年前
        1
  •  1
  •   gsamaras a Data Head    6 年前

    您要调用哪个函数是不明确的,因为作为参数传递给函数的任何l值都可以隐式转换为引用,因此,正如中所述,这种不明确是不可避免的。 Function Overloading Based on Value vs. Const Reference .

    你可以改变这个:

    void Add(T item) {}
    

    对此:

    void Add(T&& item) {}
    

    Live demo