On Wed, 9 Jun 2004 16:22:04 +0800, "Hunter Hou" <hyhou@lucent.com>
wrote:
[color=blue]
>Hello,
>
>I'm trying one example of <<the C++ programming language>> Page 865
>
>int f( int );
>template< class T > T g( T t ) { return f( t ); }
>char c = g( 'a' ); ************[/color]
The above would call int f(int) on a conforming compiler.
[color=blue]
>char f( char );
>
>Stroustrup said **** line is wrong because alternative resolution of f( t )
>are possible.[/color]
I doubt he said exactly that. He may have said something about
dependent name resolution?
[color=blue]
>But I used g++ in mingw to compile above code, there's nothing wrong.[/color]
You need g++ 3.4 (see
www.mingw.org). This is the first GCC version to
include a partial implementation of two phase name lookup in
templates.
[color=blue]
>And who can explain further about template instantiation and namespace? I
>don't quite understand what Stroustrup says.[/color]
int f( int );
The above declares a global function int f(int).
template< class T > T g( T t )
{
return f( t );
The name "f" used here is a dependent name - that is, the meaning of
it depends on the type of T. This means that lookup doesn't happen
immediately.
}
char c = g( 'a' );
Instead, lookup of the f in g is deferred until the point of
instantiation, here. Names "f" are looked up both at the point of
definition of g (where int f(int) is found), and at the point of
instantiation using argument dependent lookup (where again, int f(int)
is found, since char f(char) hasn't been declared yet). So the call to
g calls int f(int).
char f( char );
This function isn't called.
Note that GCC 3.4 still has some bugs with name lookup, so it will
call char f(char) even though it hasn't been declared at the point of
instantiation. I assume this will be fixed in GCC 3.5. However, a few
compilers do get your example right - notably Comeau C++ and other EDG
based compilers such as Intel C++ (they output a linker error for the
missing definition of int f(int) - GCC outputs a error for char
f(char) which is incorrect).
There is only one book that covers these name lookup issues in detail,
and that's Vandevoorde and Josuttis' book, "C++ Templates". Worth a
read (although I haven't read it myself).
Tom
--
C++ FAQ:
http://www.parashift.com/c++-faq-lite/
C FAQ:
http://www.eskimo.com/~scs/C-faq/top.html