2

I am new to template classes, and tried to implement a very simple program, just to try out the functionality and syntax. I initialise a template class distance, and then try to get the data and display it.

#include<iostream>
using namespace std;

template <class T>

class distance {

T feet;
T inches;

public:
    distance ()
    {

    }
T getdata (T f, T i)
{
    feet=f;
    inches=i;
}
void showdata ()
{
    cout<<"Distance is "<<feet<<" feet and "<<inches<<" inches";
}

};

int main ()

{

    distance <int> x;
    x.getdata(5,7);
    x.showdata();


}

However, on the distance <int> x line, I get the error stating 'error: reference to 'distance' is ambiguous'. I am not able to figure out my error.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
  • 1
    Unable to reproduce your compilation error. This is obviously not the code that produces the compilation error. Your shown code fails to meet all requirements for a [mre], therefore nobody will be able to help you; at most you can expect are random guesses as to what the problem might be. Although I think I have a pretty good guess as to the common error that has this result, I cannot be sure, due your failure to provide a [mre], to confirm it. – Sam Varshavchik Feb 13 '20 at 03:47
  • I have edited it to include the header files and library that I used. Is that what you were referring to? – Pranav Krishnan Feb 13 '20 at 03:52
  • 1
    Yes, and now this confirmed what I suspected. – Sam Varshavchik Feb 13 '20 at 03:57

1 Answers1

2
using namespace std;

You've just discovered why using namespace std; is bad practice.

This injects the C++ library's std::distance template into your program's global namespace, causing a name conflict with your own distance template.

Removing this, replacing all couts with std::couts, and fixing the return value from getdata() fixed all compilation errors.

Use this as a learning lesson: avoid using namespace std; in the future, or be prepared to deal with mysterious compilation errors.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148