内建的下标索引操作符的可交换性,不管是数组还是指针,它们的下标索引表达式都可以“反过来写”,像这样:正常写法 int ar[5]; int *p = ar;求 a[n]或p[n]的值。 另类写法:求n[ar]和n[p]的值。
为什么会有n[ar]或n[p]的这种写法?它在作为C++的另一个领域----泛型编程中确实可以带来一个实际的好处。这种下标索引的可交换性只对内建的下标索引操作符有效,这一限制可以用于约束一段代码只对数组或/指针有效,而拒绝重载了下标索引操作符的类类型。具体做法像这样:
template<typename T>void reject_subscript_operator(T const &t){sizeof(t[0]); // 如果T不能进行下标索引的话,编译器就会在这里打住sizeof(0[t]); // 如果T只能支持用户自定义的下标索引操作符,编译器也会在这里报错}void reject_subscript_operator( void const * const){}void reject_subscript_operator(void *){}int _tmain(int argc, _TCHAR* argv[]){void *pv = &pv;
void const *pcv = pv;int ai[100];
int *pi = ai;
Pointer ptr;Subscript subscr;reject_subscript_operator(pv);reject_subscript_operator(pcv);reject_subscript_operator(ai);reject_subscript_operator(pi);reject_subscript_operator(ptr);reject_subscript_operator(subscr); // error
return 0;
}