That's my thinking about the auto and decltype:
The most obvious difference in pratice between the two is:
- In type deduction for expr,
decltype
deduce the correct type( except the lvalue expr -> lvalue ref) and auto
default to value.
We need to learn the "data stream" model before understanding the difference.
In our codes, the function calling can be resolved as a data stream model(something like the concept of functional program), so the function which is been called is the data receiver, and the caller is the data provider. It is obviously that the data type must be decided by the data receiver, or the data cannot be organized in order in the data stream.
Look this:
template<typename T>
void foo(T t){
// do something.
}
the T will be deduced to a value type, regardless of whether you pass.
If you want the ref type, you should use auto&
or auto&&
, that's what I am saying, the data type is decided by the data receiver.
Let's return to the auto
:
auto
is used to do a type deduction for rvalue expr, giving the data receiver a correct interface to receive the data.
auto a = some expr; // a is data receiver, and the expr is the provider.
So why dose auto
ignore the ref modifier?
because it should be decided by the receiver.
Why we need decltype?
The answer is : auto
cannot to be used as a true type deduction, it will not give you the correct type of a expr. It just give the data receiver a correct type to receive the data.
So, we need decltype to get the correct type.