embarrassing question

Started by
9 comments, last by Ezbez 16 years ago
Why can't I do the following?

#include <iostream>
#include <utility>
#include <complex>

using namespace std;

typedef pair<double, double> point;

double distance (const point& p1, const point& p2)
{
	double a, b, c;

	a = p2.first-p1.first;
	b = p2.second-p1.second;
	c = sqrt ((a*a) + (b*b));
	return c;
}

int main()
{
	double d;
	point p1(-2.0, -3.0);
	point p2 (-4.0, 4.0);

	d = distance (p1, p2);  // compiler doesn't seem to like this

	cout << d << endl;
	return 0;
}
Advertisement
What is the error message?
Change the name of your distance function.

This is one of the problems with the statement "using namespace std;" - there's a LOT of stuff in the std namespace, and std::distance is one of them. As far as I can tell on my compiler (MSVC9) it's a function that returns the distance between two iterators.
NextWar: The Quest for Earth available now for Windows Phone 7.
There's a same name function in std called distance which is what the compiler thinks you're trying to call, rather than your own defined distance function. You need to specify the global scope with ::distance to call your own function.

Side note: even removing the using namespace std line, you need to specify ::distance because of Koenig lookup
omg thx! This was driving me CRAZY!

Quote:Original post by linternet
omg thx! This was driving me CRAZY!


This is why it's generally recommended not to include namespaces blindly.

std::cout << << d << std::endl isn't that much harder to write, is it?
Quote:Original post by load_bitmap_file
Side note: even removing the using namespace std line, you need to specify ::distance because of Koenig lookup


I can't say I knew anything about Koenig lookup until I just Wikipedia'd it, but from my understanding that isn't true. Since the point type is in the global namespace, Koenig lookup wouldn't associate it with the std namespace, and hence wouldn't look in std for it. Is that correct or am I misunderstanding something?
Quote:Original post by Ezbez
I can't say I knew anything about Koenig lookup until I just Wikipedia'd it, but from my understanding that isn't true.

I was skeptical, so I just tried it. It turned out he's right.
Well then, can anyone explain in more detail? That really doesn't make sense to me.
The scope that typedefs are declared in don't matter to Koenig lookup; only the base type of the types. Since pair<> is defined in namespace std, argument dependent look up operates as if the type is in defined in namespace std, since it is. Remember, typedefs don't actually define new types; they only create type aliases.

This topic is closed to new replies.

Advertisement