Re: friend function defined in the class
Lin Jen-Shin ha scritto:
class Dummy{
friend void hi(){ std::cout << "hi" << std::endl; }
};
"hi" is a namespace level function, not a method of Dummy.
Yes, but unless there's also a definition at namespace level, it won't
be found by normal lookup but only through ADL. However, in this case,
as hi() has no parameters, ADL never kicks in, so it can't be found at
all.
Consider codes below:
class Dummy{
friend void hi(){ std::cout << "hi" << std::endl; }
friend void hello(){ ::hi(); }
};
I've tried 3 compilers to compile above code, which are
a) g++ 3.4.5
b) VC++ 7.1
c) Comeau C/C++ 4.3.3
with all warning on and strict mode in standard.
g++ compiled fine, while the others failed.
Then g++ is wrong, the others right, according to me. hi() can't be
found, as I said before, even if fully qualified.
If I didn't know things wrong, which VC++ 7.1 said "argument-dependent
lookup"
was also called "Koneig Lookup", which I got from
http://en.wikipedia.org/wiki/Koenig_lookup.
And it is in standard, right?
Of course it is!
However, what makes me wonder most is that if I add codes below front
of friend:
extern void hi();
Then VC++ 7.1 and Comeau C/C++ 4.3.3 compiled fine, linked fine.
Sure, as I said, adding a namespace level declaration makes the
function visible even through normal lookup.
If I provide another definition of ::hi():
void hi(){}
then all of the compilers complained about "multi-definition" in
compile time.
Correct, because in this case you have provided two definitions for the
same function,violating ODR.
Moreover, if I didn't use strict mode in Comeau C/C++ 4.3.3, then it
compiled
fine just as g++ 3.4.5 did, no need to provide additional forward
declaration.
That's why it's called "strict" mode ;-) The rule that makes hi() not
visible through normal lookup was not present in early implementations
of C++ so it seems that Comeau "relaxed" mode is following that early
(no longer conformant) interpretation.
Hope it helps,
Ganesh
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]