public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* Question regarding template instantiation of tempory type
@ 2004-11-15 13:18 Arthur Tse
  2004-11-15 13:32 ` Eljay Love-Jensen
  0 siblings, 1 reply; 2+ messages in thread
From: Arthur Tse @ 2004-11-15 13:18 UTC (permalink / raw)
  To: gcc-help

Hello,

I encounter a problem that I'm not sure if it is a feature or a bug:

Consider the function

template<T> void f( T& ) {}

If I write

const int x = 3;
f(x);

GCC compiles, corrently deducing " T = const int " .

But, if I write

f(3);

I get
error: invalid initialization of non-const reference of type 'int&' from 
a temporary of type 'int'

GCC cannot deduce " T = const int " from a temporary type, which seems 
unreasonable to me. While I can add a const version to fix that problem:

template<T> void f( const T& ) {}

This is problematic when I want to have, say, n arguments, for this 
would require 2^n versions of a template function -- and this is what I 
am trying to do.

Thanks a lot.

Arthur Tse

^ permalink raw reply	[flat|nested] 2+ messages in thread

* Re: Question regarding template instantiation of tempory type
  2004-11-15 13:18 Question regarding template instantiation of tempory type Arthur Tse
@ 2004-11-15 13:32 ` Eljay Love-Jensen
  0 siblings, 0 replies; 2+ messages in thread
From: Eljay Love-Jensen @ 2004-11-15 13:32 UTC (permalink / raw)
  To: Arthur Tse, gcc-help

Hi Arthur,

If your parameters are constant, then you should put in "T const&" for the 
parameter type.

If the parameters are being mutated by the function (indicated by the 
absence of const), then temporaries are supposed to generate an error 
because mutating a temporary is considered a programming error by the 
compiler.  (There are a few ways to work around this situation, but it 
takes a little more work on the invocation side of the fence, and involves 
wrapping the temporary with something that returns a non-const reference to 
itself.)

HTH,
--Eljay

^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2004-11-15 13:32 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2004-11-15 13:18 Question regarding template instantiation of tempory type Arthur Tse
2004-11-15 13:32 ` Eljay Love-Jensen

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).