型指定子 decltype(C++11)
C++11 対応機能:インデックス への移動
C++11 標準には、式の型を表現する decltype キーワードと演算子が含まれます。 この機能は BCC32 に追加された C++11 機能の 1 つです。
構文
decltype 演算子の形式は以下のとおりです。
decltype ( expression )
decltype(e)
を評価する際の規則を以下に示します。
e
が識別子式の場合またはクラス メンバへのアクセスである場合、decltype(e)
は、e
で指定された識別子またはアクセサの型です。 前に示した識別子ではなく、e
がオーバーロードされた関数セットの名前である場合は、一意に決まらないので、decltype(e)
は無効です。- 上記以外で、
e
が関数呼び出しかオーバーロード演算子の呼び出しである場合、decltype(e)
は関数で返された型です。 e
が左辺値の場合は、decltype(e)
は T がe
の型であるT (T&)
への参照です。- 他のどのような状況にも当てはまらない場合、
decltype(e)
はe
の型です。
例
decltype
の考え得る使用例をいくつか以下に示します。
以下は、この例に必要な構造体や関数の宣言で、ヘッダー ファイルに記述するものです。
const int* foo() {
return new int[0];
}
struct A {
double value;
};
class B {
int value;
public:
const A* function() {
return new A();
}
};
double GetValue(int one);
long int GetValue(double d);
template<class T>
class C {
public:
T* value;
};
ソース コードは以下のとおりです。
double e;
const char *pch;
char ch;
A* a = new A();
B* b = new B();
C<B> *c = new C<B>();
decltype(pch) var1; // type is const char*
decltype(ch) var2; // type is char
decltype(a) var4; // type is A*
decltype(a->value) var5; // type is double
decltype((a->value)) var6 = e; // type is const double&
decltype(foo()) var7; // f is const int*
decltype(b->function()) var8; // type is const A*
decltype(c->value) var9; // type is B*
decltype(GetValue(e)) var10; // well-formed, the declaration is not ambiguous
decltype(GetValue) var11; // ill-formed, represents an overload function