Deduce function argument which is a reference

W

WQ

Orginally I post this question on gamedev.net, but no useful answers,
so hope I can get help here (and seems here should be a better place
for C++ questions).

According to C++ standard 2003,
14.8.2.1, paragraph 2, the last sentence,

"If P is a reference type, the type referred to by P is used
for type deduction."

Does it mean that, if a function template takes a T & as input,
T is always be used to deduce?

For example,

template <typename T>
void myFunction(T n) { ............ }
..................
int & a = anotherIntVariable;
myFunction(a);

T is deduced as int, not int &, am I right? Does the standard mean
like that?

And my more question, can "a" be deduced as int & instead of int?
Is it possible?
From the standard, I guess not possible.

Any historical or theoretical reason that reference type
can't be deduced? Maybe because reference can't live without
the real type it references to?
 
S

SG

Does it mean that, if a function template takes a T & as input,
T is always be used to deduce?

For example,

template <typename T>
void myFunction(T n) { ............ }
.................
int & a = anotherIntVariable;
myFunction(a);

T is deduced as int, not int &, am I right? Does the standard mean
like that?

Yes. 'a' is defined to be a reference. But if used in an expression,
it is just a subexpression of type int which refers to an oject (and
hence is a so-called "lvalue expression"). You can think of it as: The
type of an *expression* is never a reference.
And my more question, can "a" be deduced as int & instead of int?

Expressions have a type and a so-called "value category". Suppose,

int i;
int &r = i;

Then, there is no difference between the expression i and the
expression r. Both refer to the same int object, and both are
expressions of type int.
Is it possible?

Not using template argument deduction, no. The fact that in the above
example r is a reference but i is not is not preserved in form of a
distinguishing property of an expression (type or value category).
Any historical or theoretical reason that reference type
can't be deduced?

It is intentional. A reference is a special beast. A reference type is
not an object type. References were introduced to support operator
overloading.

Cheers!
SG
 
Q

Qi

You can think of it as: The
type of an *expression* is never a reference.

That summary is brilliant.

That really enlightened me and helped me to understand
reference deeper.

Thanks so much for the explanation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top