Reputation: 791
Have no idea about C++11 type inference
As I known, there are at least 3 type inferences in C++11:
But I can't build a concept model for them. It makes me confused.
That results in that I don't know what is right in subtle case.
In fact, I don't even know what my question is. But, I try:
I want to know how cv, & and && qualifiers affect the type inference.
I want to know what the difference is between the three kinds of type inference.
///The following extract from 14.8.2.1 in n3242
template <class T> int f(T&&);
template <class T> int g(const T&&);
int i;
int n1 = f(i); // calls f<int&>(int&)
int n2 = f(0); // calls f<int>(int&&)
int n3 = g(i); // error: would call g<int>(const int&&), which
// would bind an rvalue reference to an lvalue
///The following extract from 8.3.2 in n3242
int i;
typedef int& LRI;
typedef int&& RRI;
LRI& r1 = i; // r1 has the type int&
const LRI& r2 = i; // r2 has the type int&
const LRI&& r3 = i; // r3 has the type int&
RRI& r4 = i; // r4 has the type int&
/*The following statement encounter compilation error in gcc 4.6:error message:
invalid initialization of reference of type int&& from expression of type int*/
RRI&& r5 = i; // r5 has the type int&&
decltype(r2)& r6 = i; // r6 has the type int&
decltype(r2)&& r7 = i; // r7 has the type int&
///The following is from some blog
int i;
decltype( i ) ==> int
decltype( (i) ) ==> int &
Upvotes: 0
Views: 844
Reputation: 33385
Template deduction is in C++03
template <typename T> void foo(T) {}
int i;
float f;
foo (i); // deduces foo<int>
foo (f); // deduces foo<float>
Here the compiler sees foo(i)
and says to itself "the T
part of foo
has to be an int
for this to match".
auto
is pretty simple.
int foo ();
float bar ();
auto i = foo (); // i is an int
auto f = bar (); // f is a float
The compiler sees auto i =
and says to itself "well the right hand side yields an int
so i
will have to be one of those".
decltype
is a bit more involved, a kind of meta-auto. decltype(x)
is equivalent to int
if x
is an int
, float
if x
is a float
, etc. The advantage is that you can use it in template expressions.
int foo (float);
float foo (int);
template <typename T> void convert (std :: vector <T> input) {
std :: vector <decltype (foo(input[0]))> output;
output .push_back (foo (input [0])); // yeah, ok, not safe, meh
}
convert (std :: vector <int> ()); // Will create an output of type std::vector<float>
convert (std :: vector <float> ()); // Will create an output of type std::vector<int>
Here decltype (foo(input[0]))
is float
when input
is a vector of int
because input[0]
is an int
and the overload of foo
which takes an int
returns a float
.
Upvotes: 2