c++c++11effective-c++

Deducing the types


I am trying to understand type deduction while walking through Scott Meyer's Effective Modern C++.

Consider the code snippet below:

template<typename T>
void f(const T& param); // param is now a ref-to-const; paramType is const T&

int x = 27; // as before
const int cx = x; // as before
const int& rx = x; // as before

f(x); // T is int, param's type is const int&
f(cx); // T is int, param's type is const int&
f(rx); // T is int, param's type is const int&

He says that since the paramType is a reference, we can follow a two step procedure to deduce the type of T:

  1. Ignore references (if any) in expr (i.e., x, cx and rx)
  2. Pattern match the type of expr and paramType

Now when cx is a const int:

cx -> const int

paramType -> reference to const int

So, according to the logic mentioned, shouldn't T be a const int due to pattern matching (and not just int)? I understand that the constness of cx has been passed over to paramType, but is what he says, wrong? Is this 2 step procedure that he has mentioned not to be followed as a rule of thumb? How do you do it?

Thanks!


Solution

  • In his book Scott uses this "notation":

    template<typename T>
    void f(ParamType param); // where `ParamType` depends on T
    

    So let's do pattern matching for ParamType when param is const int. We have:

    const T & <----> const int // <----> is symbolic notation for pattern matching
    

    So T is deduced as int, hence ParamType is const int&.