Understand the type of param in void f(const T& param)

242 Views Asked by At

Reference: Effective Modern C++ Item 4.

https://github.com/BartVandewoestyne/Effective-Modern-Cpp/blob/master/Item04_Know_how_to_view_deduced_types/runtime_output02.cpp

class Widget {};

template<typename T>                // template function to
void f(const T& param)              // be called
{
}

std::vector<Widget> createVec()    // factory function
{
    std::vector<Widget> vw;
    Widget w;
    vw.push_back(w);
    return vw;
}

int main()
{
    const auto vw = createVec();        // init vw w/factory return

    if (!vw.empty()) {
      f(&vw[0]);                        // call f
      // ...
    }
}

Based on the book, the type of both T and param are as follows respectively:

T = class Widget const *
param = class Widget const * const &

I have problems to understand why the param is the given type with the f(const T& param) defined above.

Here is my understanding,

T = class Widget const *

So f(const T& param) becomes the following:

f(const const Widget * & param).

Why the real type of param is Widget const * const & instead?

2

There are 2 best solutions below

0
On BEST ANSWER

Question> Why the real type of param is Widget const * const & instead?

I'm not really an expert but... because T is a pointer and if you write const T & (that is T const & because the rule is that const apply on the element on the left or on the element on the right in there isn't an element on the left) you are imposing that the full T type, so the pointer, is constant.

And to impose that the pointer is constant, you have to impose cont on the left of the *.

In brief: const T & is equivalent to T const &; with T that is const Widget *, T const & become const Widget * const & or, if you prefer, Widget const * const &

0
On

You're confusing about const pointer and pointer to const (and then const pointer to const).

Note the position of * and const. e.g. Widget const * is a non-const pointer to const (Widget), Widget * const is a const pointer to non-const (Widget), Widget const * const is a const pointer to const (Widget).

For T = Widget const *, which is non-const pointer to const; note that for const T, const is qualified on T i.e. the pointer itself, not on the object pointed to, then const T will be Widget const * const.