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?
I'm not really an expert but... because
Tis a pointer and if you writeconst T &(that isT const &because the rule is thatconstapply 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 fullTtype, so the pointer, is constant.And to impose that the pointer is constant, you have to impose
conton the left of the*.In brief:
const T &is equivalent toT const &; withTthat isconst Widget *,T const &becomeconst Widget * const &or, if you prefer,Widget const * const &