Type Specifier decltype (C++11)

From RAD Studio
Jump to: navigation, search

Go Up to C++11 Features in the Classic Compiler

Attention: This page refers to a C++11 feature in the Classic compiler. The Classic compiler is not recommended: instead it is recommend you use the Clang-enhanced compilers, which support modern C++ including C++11, C++14 and C++17.

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

Syntax

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.

Examples

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;

public:
    const A* function() {
        return new A();
    }
};

double GetValue(int one);

long int GetValue(double d);

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(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