【问题标题】:Understand the type of param in void f(const T& param)理解 void f(const T& param) 中的参数类型
【发布时间】:2017-01-07 02:07:34
【问题描述】:

参考: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
      // ...
    }
}

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

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

我很难理解为什么param 是上面定义的f(const T&amp; param) 的给定类型。

这是我的理解,

T = class Widget const *

所以f(const T&amp; param) 变成了以下内容:

f(const const Widget * &amp; param).

为什么param的真正类型是Widget const * const &amp;

【问题讨论】:

  • T = class Widget const * param = class Widget const * 在 Visual Studio 2017 RC 上

标签: c++ c++11 templates constants auto


【解决方案1】:

问题>为什么真正的param类型是Widget const * const & 而不是?

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

为了使指针保持不变,您必须在* 的左侧加上cont

简而言之:const T &amp; 等价于T const &amp;Tconst Widget *T const &amp; 变为 const Widget * const &amp;,或者,如果你愿意,Widget const * const &amp;

【讨论】:

    【解决方案2】:

    您对 const pointerpointer to const(然后是 const pointer to const)感到困惑。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-18
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 2021-11-05
      相关资源
      最近更新 更多