I am kind of confused about template type deduction. But when it comes to auto it gets more confusing. I hope the example I try to supply can sum up my confusion.
std::unordered_map<std::string, int> _m;
//.......
for(auto _pair : _m)
{
// do stuff
{
Now normally each element of the map is
std::pair<const std::string, int>
My question is that does the code that I write inside the for loop have an effect on the type deduced by the auto? Does compiler try to find a way to match the code inside the loop with what auto deduces?
auto
is determined purely in the context of the code initializing the value, not subsequent usage. Trying to deduce one of several possible alternative types based on an arbitrary amount of subsequent code would lead to effectively unbounded complexity in the type deducer.
It's why clever tricks like GMP's "expression types" (used to avoid calculating a value until assignment when subsequent mathematical operations might lead to a more efficient solution) don't work properly with type deduction; using auto
with them would try to store the intermediate expression, not a realized mpz_class
or the like, even if subsequent code requires a realized type.