Search code examples
c++c++11pointersautotype-deduction

auto type deduction when ParamType is neither a Pointer nor a Reference


I referred to Scott Meyers "More Effective C++" for auto type deduction. It is mentioned that is works the same way as Template type deduction, and there are 3 cases mentioned. My question falls into case 3 (when ParamType is not a pointer or reference), but the outcome is not matching what is described.

#include <iostream>

int main (void)
{
   auto i = 2;
   const auto c = &i;

   *c = 4;

   std::cout << "i is " << i;
}

It should work as

template<typename T>
void f(const T param);

f(&i);   // int *

So, T here should match to int * and the complete type of param should be const int *.

But, as the program above shows, c is not const int * but is int *.

Can someone explain what am I missing here?


Solution

  • When you have

    template<typename T>
    void f(const T param);
    

    and T is a pointer type you don't have const type * but instead type * const since you are making what T is const, not what it points to.

    That means

    const auto c = &i;
    

    is a int * const, a constant pointer to a non constant integer.