在这个示例中,
const
被应用于
auto
所推断的任何内容,这意味着两种用法都会产生一个
int * const
类型的对象,因为
auto
本身推断出
int *
。你所想象的排序是基于你是否写成
auto const
或
const auto
,但实际上并没有发生,就像
int const
和
const int
是一样的。
更容易理解的方法可能是尝试以下操作:
template<typename T>
using pointer = T*;
pointer<int> ptr_to_int = new int;
const pointer<int> const_ptr_to_int = new int;
pointer<const int> ptr_to_const_int = new int;
const pointer<const int> const_ptr_to_const_int = new int;
pointer<int> const const_ptr_to_int2 = new int;
pointer<int const> ptr_to_const_int2 = new int;
pointer<const int> const const_ptr_to_const_int2 = new int;
pointer<int const> const const_ptr_to_const_int3 = new int;
在此示例中,只有名称末尾数字不同的变量是等效类型,就C++而言。请注意,更改
const
出现的位置不会影响推断的类型。这是因为“从右到左”阅读以确定如何声明类型的规则基于原始类型的编写方式:一旦使用了这样的结构(或者,如您所观察到的那样,
auto
),规则就变得简单得多。
我的直觉是,由于您的问题暗示您需要对类型系统进行这种细粒度控制,因此应该像我在这里展示的那样,在
pointer<T>
上使用
using
或
typedef
,并使用它来声明您的类型,因为这样一眼就可以知道
const pointer<int>
是什么,而不是看到
int *const
是什么。特别是因为它可以防止愚蠢的错误,比如这样的错误:
int * a_ptr, b_ptr, c_ptr; //Oops! We meant b_ptr and c_ptr to also be pointers, but
//they ended up being regular ints!
pointer<int> a_ptr, b_ptr, c_ptr; //All of these are pointers, as we expected them to be
< p >
auto
技术上也可以解决这个问题,但正如你在示例中展示的那样,你仍然不确定
const
是被应用于指针本身还是它所指向的对象,而在这种情况下,就没有更多的歧义了。
using T = int *; const T
->int *const
。 - HolyBlackCatconst auto
和auto const
是相同的类型。示例 - BiagioFauto
使用 模板参数推导 的规则。 - wally