【问题标题】:auto type deduction when ParamType is neither a Pointer nor a ReferenceParamType 既不是指针也不是引用时的自动类型推导
【发布时间】:2018-03-22 15:57:37
【问题描述】:

我参考了 Scott Meyers “更有效的 C++” 来进行自动类型推断。提到它的工作方式与模板类型推导相同,并且提到了3种情况。我的问题属于案例 3(当 ParamType 不是指针或引用时),但结果与描述的不匹配。

#include <iostream>

int main (void)
{
   auto i = 2;
   const auto c = &i;

   *c = 4;

   std::cout << "i is " << i;
}

它应该像

template<typename T>
void f(const T param);

f(&i);   // int *

所以,这里的T 应该与int * 匹配,param 的完整类型应该是const int *。

但是,正如上面的程序所示,c 不是const int *,而是int *。

有人可以解释我在这里缺少什么吗?

【问题讨论】:

  • 如果T 是int *,那么const T 是int *const,而不是const int *。

标签: c++ c++11 pointers auto type-deduction


【解决方案1】:

当你有

template<typename T>
void f(const T param);

而T 是一个指针类型,你没有const type *,而是type * const,因为你正在使T 是const,而不是它所指向的。

意思是

const auto c = &i;

是一个int * const,一个指向非常量整数的常量指针。

【讨论】:

    猜你喜欢
    • 2018-01-28
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多