vendredi 25 novembre 2016

C++ member function is ambiguous

I've seen there are already questions about ambiguous error in C++, but this is some kind of different.

Let's say we have code like following:

#include <iostream>

#define LDBG(msg) \
  std::cout << "[" << __FUNCTION__ << " " << __LINE__ << "] " << msg << std::endl;

template<typename T>
struct AClass{
  AClass(T a) {}

  void Foo(const AClass<T> &other){
    LDBG("")
  }

  void Foo(const T &key) const{
    LDBG("")
  }
};

int main(){
  AClass<int> a1{1};
  AClass<int> a2{2};

  a1.Foo(1);
  a1.Foo(a2);

  LDBG("")
  return 0;
}

This will produce compiling error like:

error: call to member function 'Foo' is ambiguous
    a1.Foo(1);
    ~~~^~~
note: candidate function
    void Foo(const AClass<T> &other){
         ^
note: candidate function
    void Foo(const T &key) const{
         ^
1 error generated.

The error will just be gone if:

  1. Remove the const at line 14 ( void Foo(const T &key) const{ )

or 2. Add a const at the end of void Foo(const AClass<T> &other) too

or 3. Change the Constructor into AClass() {} (also the relative Initialization of a1 and a2 in main function)

or some other ways.

Why?

Aucun commentaire:

Enregistrer un commentaire