Reference: Effective Modern C++ Item 4.
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?
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 &