了解 void f(const T& param) 中参数的类型

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

参考:有效的现代 C++ 项目 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
      // ...
    }
}

根据书本,Tparam的类型分别如下:

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

我无法理解为什么 param 是上面定义的 f(const T& param) 的给定类型。

这是我的理解,

T = class Widget const *

所以f(const T& param)变成如下:

f(const const Widget * & param).

为什么 param 的真实类型是 Widget const * const &

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

我不是真正的专家但是...因为 T 是一个指针,如果你写 const T & (即 T const & 因为规则是 const 应用于左侧的元素或右侧的元素(因为左侧没有元素)你强加了完整的 T 类型,因此指针是常量。

并且要强制指针是常量,您必须在 * 的左侧施加 cont

简而言之:const T &等同于T const &Tconst Widget *T const & 变为 const Widget * const & 或者,如果您愿意,Widget const * const &

您混淆了 const 指针const 指针(然后 const 指针指向 const).

注意*const的位置。例如Widget const * 是指向 const (Widget) 的非常量指针,Widget * const 是指向非常量 (Widget) 的 const 指针,Widget const * const 是 const指向 const (Widget).

的指针

对于T = Widget const *,这是指向const的非常量指针;请注意,对于 const Tconst 是在 T 上限定的,即指针本身,而不是在指向的对象上,那么 const T 将是 Widget const * const.