eg4
数据类型(Rule-1) int a[10]; decltype(a) //
int[10]
eg5 成员变量(Rule-1) class A {
int a; int& b; static int
c;
void foo()
{
decltype(a) //
int
decltype(this->a) //
int decltype((*this).a) //
int
decltype(b) //
int&
decltype(c) // int (static
members are treated as variables in namespace scope)
} void bar() const
{ decltype(a) //
int decltype(b) //
int& decltype(c)
// int } };
A aa; const A& caa =
aa; decltype(aa.a) // int decltype(aa.b) //
int& decltype(caa.a) //
int
但内置操作符.*和->*适用Rule-3: decltype(aa.*&A::a)
// int& decltype(aa.*&A::b) // illegal, cannot take the address of a
reference member decltype(caa.*&A::a) // const int&
eg7 指向成员变量和成员函数的指针(Rule-1) class A
{ int x; int&
y; int foo(char); int& bar()
const; };
decltype(&A::x) // int
A::* decltype(&A::y) // error: pointers to reference
members are disallowed (8.3.3 (3)) decltype(&A::foo) // int (A::*)
(char) decltype(&A::bar) // int& (A::*) () const
eg8
字面值(Rule-3) (字符串字面值是左值,其它字面值都是右值) decltype("decltype") // const
char(&)[9] decltype(1) // int
eg9
冗余的引用符(&)和CV修饰符 由于decltype表达式是一个类型别名,因此冗余的引用符(&)和CV修饰符被忽略: int&
i = ...; const int j = ...; decltype(i)&
// int&. The redundant & is ok const decltype(j) // const
int. The redundant const is ok
eg10 函数调用(Rule-2) int
foo(); decltype(foo()) // int float&
bar(int); decltype (bar(1)) // float& class A { ... }; const
A bar(); decltype (bar()) // const A const A&
bar2(); decltype (bar2()) // const A&
eg11
内置操作符(Rule-3) decltype(1+2) // int (+ returns an
rvalue) int* p; decltype(*p) //
int& (* returns an lvalue) int a[10]; decltype(a[3]); //
int& ([] returns an lvalue) int i; int& j = i; decltype (i =
5) // int&, because assignment to int returns an
lvalue decltype (j = 5) // int&, because assignment to int
returns an lvalue decltype (++i); // int& decltype
(i++); // int
(rvalue)
如何用程序验证decltype的结果?可以参考下面的程序对上面的分析结果进行验证: F:\tmp>type
decltype_eg1.cpp #include <iostream> #include
<string> using namespace std;
F:\tmp>a.exe a: int b: int& c: const
int& d: const int e: A f: unknown
F:\tmp>gcc
--version gcc (GCC) 4.3.0 20080305 (alpha-testing)
mingw-20080502 Copyright (C) 2008 Free Software Foundation, Inc. This is
free software; see the source for copying conditions. There is
NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.