Possible Duplicate:
deducing references to const from rvalue arguments
If I have
template<class T>
void foo(T &) { }
and I call it as foo((const int)5)
, given that the argument is a const int
, why doesn't the compiler automatically infer T
to be const int
?
It does, if it's given a const type. Rvalues (prvalues in C++11) with
non-class types, however, are never cv-qualified, even if you try to say
they are: the expression ((const int)5)
has type int
. The reasoning
here is that cv-qualifications only apply to objects, and temporaries of
non-class types aren't objects, but pure values; cv-qualifications can't
apply, because there's nothing to be const
or volatile
.
If you write:
int const i = 42;
foo( i );
, your template will instantiate with T = int const
. (As you
wrote it, the code shouldn't compile, because the deduced type
is int
, so the function takes an int&
, which can't be
initialized with an rvalue.)