In the code below, what are the types of a and b?
template <class T = const int&>
struct A
{
T& a;
T b;
};
int main() {
int i = 1;
A<> a{i, i};
return 1;
}
I used the code from this post that can give the type of a variable. -> post
But, it says both types are i const&
.
int main() {
int i = 1;
A<> a{i, i};
std::cout << type_name<decltype(a.a)>() << std::endl;
std::cout << type_name<decltype(a.b)>() << std::endl;
return 0;
}
Are T&
and T
be the same type in the above case?
Do those ampersands combine and become r-value or some other rule?
T
isconst int&
because that's what you told it to be.T&
is alsoconst int&
because reference collapsing transforms yourT&
intoT
:This is for convenience, because there is no such thing as
const int& &
(reference to reference; not to be confused with rvalue reference typeconst int&&
which does exist!) and it's handy to be able to just write code like yours without having to manually "get rid of" the "extra"&
.The rationale behind this rule is explained in more detail here: