Namespace & template puzzle

J

James W. Walker

Can someone please explain to me why the following code gives a compile
error when instantiating the sort algorithm?

#include <vector>

namespace
{
struct Foo {
int m;
};
}

static bool operator<( const Foo& inOne, const Foo& inTwo )
{
return inOne.m < inTwo.m;
}

static void test()
{
std::vector<Foo> vec;
std::sort( vec.begin(), vec.end() );
}

It's as if it doesn't understand that I have provided operator< for
Foo. But if I just say

Foo x,y; if (x < y) {... }

instead of sorting, there is no problem. If I move the operator< into
the namespace, then it compiles. So, I know how to fix it, but I'd
like to understand it.
 
B

Bob Hairgrove

Can someone please explain to me why the following code gives a compile
error when instantiating the sort algorithm?

#include <vector>

namespace
{
struct Foo {
int m;
};
}

static bool operator<( const Foo& inOne, const Foo& inTwo )
{
return inOne.m < inTwo.m;
}

static void test()
{
std::vector<Foo> vec;
std::sort( vec.begin(), vec.end() );
}

It's as if it doesn't understand that I have provided operator< for
Foo. But if I just say

Foo x,y; if (x < y) {... }

instead of sorting, there is no problem. If I move the operator< into
the namespace, then it compiles. So, I know how to fix it, but I'd
like to understand it.

By putting Foo() into an anonymous namespace, it is hidden from
everything outside that namespace.
 
J

James W. Walker

Bob Hairgrove said:
By putting Foo() into an anonymous namespace, it is hidden from
everything outside that namespace.

I don't see how that is consistent with what happened. My definition
of operator< for Foo was outside the namespace, and I didn't get a
compile error on that.
 
O

Oplec

James said:
I don't see how that is consistent with what happened. My definition
of operator< for Foo was outside the namespace, and I didn't get a
compile error on that.

I'm new to C++, but from what I have read about anonymous namespaces,
whatever is included in an anonymous namespace is only accessable from
within the single translation unit that it is defined in. Maybe that has
something to do with it.

Oplec.
 
S

Stephen M. Webb

James W. Walker said:
Can someone please explain to me why the following code gives a compile
error when instantiating the sort algorithm?

I believe this is an effect of Koenig lookup rules.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,145
Messages
2,570,826
Members
47,371
Latest member
Brkaa

Latest Threads

Top