Discover The C++ Declared Type of Expression Feature In Windows Development
Declared type of an expression is a feature supported by both BCC32 and the Clang-enhanced C++ compilers. The decltype type specifier is used to obtain the type specifier of an expression. This feature is one of the C++11 features.
decltype(expression) takes expression as an operand. When you define a variable by using decltype(expression), it can be thought of as being replaced by the compiler with the type or the derived type of expression. Consider the following example:
int i; static const decltype(i) j = 4;
In this example, decltype(i) is equivalent to the type name int.
General rules for using decltype
- If expression is an un-parenthesized id-expression or class member, decltype(expression) is the type of the entity named by expression. If there is no such entity, or if expression names a set of overloaded functions, the program is ill formed.
- Otherwise, if expression is a function call or an invocation of an overloaded operator (parentheses around expression are ignored), decltype(expression) is the return type of the statically chosen function.
- Otherwise, if expression is an lvalue, decltype(expression) is T&, where T is the type of expression.
- Otherwise, decltype(expression) is the type of expression.
Examples
Here are the declarations of the structures and functions needed for the example, that should be placed in the header file:
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); template<class T> class C { public: T* value; };
Here is the source code:
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(b->function()) var7; // type is const A* decltype(c->value) var8; // type is B* decltype(GetValue(e)) var9; // well-formed, the declaration is not ambiguous decltype(GetValue) var10; // ill-formed, represents an overload function
Leave Your Comment