embarrassing question

This topic is 3743 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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;
}


Share on other sites
What is the error message?

Share on other sites
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.

Share on other sites
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

Share on other sites
omg thx! This was driving me CRAZY!

Share on other sites
Quote:
 Original post by linternetomg 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?

Share on other sites
Quote:
 Original post by load_bitmap_fileSide 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?

Share on other sites
Quote:
 Original post by EzbezI 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.

Share on other sites
Well then, can anyone explain in more detail? That really doesn't make sense to me.

Share on other sites
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.

• 11
• 19
• 12
• 34
• 9
• Forum Statistics

• Total Topics
631398
• Total Posts
2999838
×