-1
using namespace std;
#include <iostream>
#include <cstring>

struct distance {
    int Kilometer;
    int Meter;
    int Centimeter;
};

distance add() {
}

int main() {
    return 0;
}

Trying to define a function that returns a "distance" data type. I'm getting hit with "distance is ambiguous" when trying to define the function.

zomy2000
  • 73
  • 4
  • 6
    This is why you shouldn't include `using namespace std;`. See [std::distance](https://en.cppreference.com/w/cpp/iterator/distance). – 1201ProgramAlarm Jan 17 '20 at 01:44
  • @1201ProgramAlarm I get that std::distance exists, but I’m not sure I see how this would result in an ambiguity here. Is there a way to parse this code other than as a function returning a distance? – templatetypedef Jan 17 '20 at 02:02
  • 3
    By using `using namespace std;`, you bring `std::distance` into the same scope as your `distance` struct. That is why your code is ambiguous - the compiler doesn't know which `distance` to use. – Remy Lebeau Jan 17 '20 at 02:07

2 Answers2

6

As @1202ProgramAlarm points out in the comments, this is a classic reason why you should never include using namespace std;. Because you've introduced the std namespace, the compiler isn't sure what distance you mean: your custom struct distance, or std::distance, hence "distance is ambiguous".

The easiest and best fix is to not use using namespace std. Sure you might spend a few moments extra writing std:: but you will save yourself from these headaches.

You could also rename your struct to be Distance, or you could qualify it with ::distance add()

Tas
  • 7,023
  • 3
  • 36
  • 51
4

Change the struct name, define it in any namespace, or don't use using namespace std; because there is already a function called distance() in the std namespace.

#include <iostream>
#include <cstring>

namespace myNamespace{

    struct distance {
        int Kilometer;
        int Meter;
        int Centimeter;
    };

    distance add() {

        return distance();
    }
}

using namespace std;

int main() 
{
    myNamespace::distance d1;
    d1 = myNamespace::add();

    return 0;
}

In general using namespace std; is bad practice, see Why is "using namespace std;" considered bad practice?.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
asmmo
  • 6,922
  • 1
  • 11
  • 25