了解 void f(const T¶m) 中的参数类型
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
// ...
}
}
根据本书,T
和param
的类型分别如下:
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 &
?
问题>为什么参数的真正类型是 Widget const * const 和代替?
我不是真正的专家,但是...因为T
是一个指针,如果你写const T &
(这是T const &
因为规则是const
应用于左侧的元素或右侧的元素,因为左侧没有元素)你正在强加完整的T
类型,所以指针, 是恒定的。
要强制指针是恒定的,您必须在*
的左侧强加cont
。
简而言之:const T &
等同于T const &
;有了const Widget *
T
,T const &
变得const Widget * const &
,或者,如果你愿意,可以Widget const * const &
你对常量指针和指向常量(然后是常量指针到常量)感到困惑。
注意*
和const
的位置,例如 Widget const *
是指向常量(Widget
)的非常量指针,Widget * const
是指向非常量(Widget
)的常量指针,Widget const * const
是指向常量(Widget
)的常量指针。
对于 T = Widget const *
,它是指向 const 的非常量指针;请注意,对于 const T
,const
限定在T
即指针本身,而不是指向的对象,那么const T
将被Widget const * const
。
- 扩展C++生成的代码的模板参数类型名称
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 在 C++ 中运行时调用模板时,是否可以切换模板的参数类型?
- 将函数参数类型声明为 auto
- 将函数的参数 - 签名从使用 'std::function<T>' 转换为模板参数类型
- 在 C++17 中调用具有不同参数类型的构造函数
- 具有先前参数类型匹配的参数包
- 我想知道为什么"std::unique_ptr<int> foo(新 int)"是合法的,因为"std::<int>unique_ptr"要求输入参数类型应该是"int"?
- 将可变参数类型列表的扩展打包为复杂类型的初始值设定项列表 - 合法吗?
- MSVC 错误:4 个重载中的任何一个都无法转换所有参数类型
- 使用constexpr + auto作为返回和参数类型的奇怪类型推导
- 如何从第一个参数推断第二个参数类型?
- C++模板函数中,指定回调函子/lambda 的参数类型,同时仍允许内联?
- 如何用不同的参数类型和数字回调函数
- C++stoi:这两个重载都无法转换所有参数类型
- 为什么std::{container}::template不能推导其参数类型
- 为模板参数类型中的新对象分配内存
- 为指向成员模板参数的指针推导额外模板参数类型的紧凑方式
- 使用std::conditional中的模板来确定函数参数类型
- C++中的短参数类型