Type Specifier decltype (C++0x)

From Appmethod Topics
Jump to: navigation, search

Go Up to C++0x Features Index

The C++0x standard includes the decltype keyword and operator, which represents the type of an expression. This feature is one of the C++0x features added to BCC32.


The format of the decltype operator is:

decltype ( expression )

Here are the rules for evaluating decltype(e):

  • If e is an identifier expression or is accessing a class member, decltype(e) is the type of the identifier or accessor designated by e. If there is no such thing, or if e is the name of a set of overloaded functions, so there is ambiguity, decltype(e)is invalid.
  • Otherwise, if e is a function call or invokes an overloaded operator, decltype(e) is the type returned by the function.
  • Otherwise, if e is an lvalue, decltype(e) is a reference to T (T&), where T is the type of e.
  • If none of the other cases apply, decltype(e) is the type of e.


This example shows some possible usage cases of decltype.

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;

	const A* function() {
		return new A();

double GetValue(int one);

long int GetValue(double d);

template<class T>
class C {
	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(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

See Also