Re: Namespace goes with template?
xman wrote:
I defined namespace hpc in main.cpp, so not to clash with other
libraries. But I found that, in namespace boo, instantiating a
template with a class in namespace hpc, causes compilation errors by
clashing the functions in the two namespaces. Is it a compiler bug? or
intended C++ behavior?
I believe it's intended.
Appreciate if any one can shed some lights for me.
See following:
func.h: In function 'void boo::rfunc(const boo::R<T>&) [with T =
hpc::B]':
main.cpp:16: instantiated from here
func.h:13: error: call of overloaded 'work(const boo::R<hpc::B>&)' is
ambiguous
func.h:5: note: candidates are: void boo::work(T) [with T =
boo::R<hpc::B>]
main.cpp:23: note: void hpc::work(T) [with T =
boo::R<hpc::B>]
I think you're running into a case of ADL (Argument-Dependent name
Lookup). To figure out which function to call, the compiler is allowed
to look in the namespaces of arguments (and of template arguments). In
your case, since when instantiating 'boo::rfunc<T>', 'R' is from 'boo'
and 'T' (deduced as 'hpc::B') is from 'hpc' namespace. Both namespaces
are considered making 'work' symbol ambiguous.
func.h:
namespace boo {
template <typename T>
void work(T n) { std::cout << "good bye work" << std::endl; }
template <typename T> class R { };
template <typename T>
void rfunc(const R<T>& a) { work(a); }
} // namespace boo
main.cpp:
#include <iostream>
#include "func.h"
A side note: here you made inclusion of 'func.h' dependent on the
previous inclusion of <iostream>. Better to avoid this. Consider
including <iostream> in 'func.h', and still keep it here because
this module uses 'cout' and 'endl' as well.
using std::cout;
using std::endl;
namespace hpc {
class B { };
class A {
public:
void bfunc(void) { rfunc(n); }
protected:
boo::R<B> n;
};
template <typename T>
void work(T n) { cout << "hello world work" << endl; }
} // namespace hpc
using hpc::A;
int main(int argc, char* argv[])
{
A a;
a.bfunc();
return 0;
}
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask