Does it have to be hard to overload functions across namespaces?
I have been writing s开发者_如何学Come code with basically this structure
namespace util {
void read (int &);
template <typename T>
void read (T &);
}
void foo ();
using namespace util;
namespace { // A
void read (MyType &, int);
void do_something () {
MyType t;
int i;
// using util::read; // B
read (i); // C
read (t,i); // D
}
}
void foo () {
do_something ();
}
At first line C wasn't compiling unless I fully qualify it as util::read(i)
or uncommented line B, but that makes line D fail.
Specialising the template util::read isn't possible because the number of arguments is different (until C++0x).
Turning line A into namespace util
isn't an option because I don't want to export the new read
.
I could rename read(MyType&,int)
but that breaks ahem style.
Is there a way to make these cross-namespace overloads work nicely? Is there a good reason that they shouldn't?
Yes, it's hard. In fact, it's impossible.
The best you can do is to hide names. You're right to employ using
(B) to get around the complications that name hiding brings into the mix, when you're also overloading functions — D should still function in this case. Please show the error you got for it.
Different namespaces mean different full names of identifiers contained in them so they are not overloads of each other (at least for Microsoft's compiler and GCC - I'm not sure how the standard defines).
Try this:
namespace util {
void read (int &);
template <typename T>
void read (T &);
}
void foo ();
namespace { // A
using ::util::read;
void read (MyType &, int);
void do_something () {
MyType t;
int i;
// using util::read; // B
read (i); // C
read (t,i); // D
}
}
void foo () {
do_something ();
}
精彩评论