Search code examples
c++pointerstemplatesconstants

How are templates work so that the classes are properly generated by the compiler to work with both pointer types and non pointer types?


Given

int i = 42;
int* p = &i;

we cannot do

const int * & d = p;

In my current understanding, this is because const int * & d can be read as "d is a reference of a pointer to an int that is a const" and p is "a pointer to an int", which means the RHS needs to be turned into a temporary being "a pointer to an int that is a const" and that cannot be binded directly with a reference (as on the LHS). We would need to have, say, const int* const& d = p;. Possible references: 1, 2.

That said, consider the following toy code:

template<typename T>
class X
{
public:
    void fun(const T& d) {  }
};

At first, I thought if I do

X<int*> x;
x.fun(p);

The method generated by the compiler would be void fun(const int*& d), and I would get an error due to the above reason.

However, there is no error and it works "as expected" (by that I mean, we always have d itself as the const no matter T is replaced by pointer types or by non-pointer types).

My current guess is that, for the above scenario, the method generated by the compiler is something like void fun(int* const& d).

May I ask if my guess is correct? How are templates work so that the classes generated by the compiler work with pointers "as expected"?


Solution

  • Your guess is correct.

    For const T, const is qualified on type T directly. Given T is int* (non-const pointer to non-const int), const T results in const pointer, i.e. int* const (const pointer to non-const int) but not const int* (non-const pointer to const int).