Re: friend declaration non-template warning
Jeff Koftinoff wrote:
Hi Everyone. I am using CRTP in class which declares a friend
function, which is not a template. It all works fine but on g++ 4.1 I
get an interesting warning, even without -Wall enabled.
Usually when I write code that generates a warning I stop and try to
look hard at what I am doing and why it is wrong or potentially
dangerous. But I can't figure out why this code deserves a warning.
Does anyone know where the idea is behind this warning? Is my code
problematic?
I don't think so. I think it is a fairly standard idiom. But...
I think class 'A' shouldn't care if the friend function is a
non-template function... It is overloaded based on a template
argument...
No problem with that. The problem is that, apparently, many
programmers expect your friend declaration to declare the
specialization of a template function as a friend, rather than
declaring a non-template function as friend. I'm just guessing,
but I can easily imagine that the maintainers of g++ just got
tired of killing bug reports because code like the following
failed to compile.
template< typename T >
class X { friend void f( T& ) ; int privateMember ; /* ... */ } ;
template< typename T >
void f( T& obj )
{
++ obj.privateMember ;
}
The warning makes it clear in this case that the error is in the
code, and not in the compiler.
---compile warnings--
make friend
g++ friend.cpp -o friend
friend.cpp:19: warning: friend declaration 'void do_something(T&)'
declares a non-template function
friend.cpp:19: warning: (if this is not what you intended, make sure
the function template has already been declared and add <> after the
function name here) -Wno-non-template-friend disables this warning
I think it's actually a very good warning. If you don't know
what you're doing, and have written something like the above, it
tells you what you should do to get what you wanted. And if you
do know what you are doing, and want exactly what you've written
(which is the case if you are using CRTP), then it tells you how
to disable the warning.
On a more philosophical level: no warning can be appropriate for
every case. If it were, we'd just adopt it into the standard as
an error. My general approach is to start by activating the
maximum number of warnings possible, then turning off the ones
that aren't relevent for my code or style. Note that with g++,
this means a lot more than -Wall, to begin with; -Wall is sort
of a compromize, that the authors of g++ felt would be
applicable to a large body of programmers. But like most
compromizes, it is ideal for no one.
--
James Kanze (Gabi Software) email: james.kanze@gmail.com
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]