Why does template parameter deduction for T 'skips' the constness of array elements when function parameter is const reference to T?

二次信任 提交于 2019-12-05 16:59:33

Using this function template prototype:

template <typename T> void func(const T& a);

In your first example, the type deduction works as:

const int* ip;

func(ip) => func<const int*>(const (const int*)& a)
                 ^^^^^^^^^^         ^^^^^^^^^^

Note: This is pseudocode. The full type is const int* const&.

Note that the const int remains const int, but the * becomes * const.

This is because const int* is just a regular, mutable, non-volatile pointer. It is just a *. What it points to is irrelevant.

But in the second example, you have:

const int ia[3];

func(ia) => func<int[3]>(const (int[3])& a)
                 ^^^^^^         ^^^^^^

Note: This is pseudocode. The real type would be const int (&a)[3].

So the type deduction is working the same in both cases, discarding the outer const.

It so happens that a const array is the same as an array of const elements.

It might help to write types like this:

template <typename T> func(T const & a);

int const * ip;

func(ip) => func<int const *>(int const * const & a)

int const ia [3];

func(ia) => func<int [3]>(int const (& a) [3])

On that second example, the const appears to "move" from being applied on the array to being applied on the elements. This is because you can't really have a const array, only an array of const elements.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!