C++11 Tidbits: Decltype (Part 1)

Decltype was among the first C++11 features implemented in GCC. It has roots in a very old GNU extension named __typeof__, also usable in C and well known to users of the GNU Compiler Collection. The C++11 conforming implementation of the idea landed in GCC 4.3.x in 2008. It overcame some defects of __typeof__. Both decltype and __decltype are available in GCC; the former only in c++11 mode, the latter both in c++11 and c++98 mode. The legacy __typeof__ is now unmaintained, meaning no problematic aspects with it will be addressed in future, besides of course making sure that what used to work keeps on working.

That said, let's introduce the basic concept of decltype. In its essence it's quite simple: the decltype operator queries the type of an expression. When this is integrated with other C++11 features it can enable rather interesting programming constructs.

A range of basic examples (from the ISO Document N2343. See some of the references therein for historical background and rationale) follows:

  const int&&;& foo();
  int i;
  struct A { double x; };
  const A* a = new A();

  decltype(foo())  x1;  //  type is const int&&      (1)
  decltype(i)      x2;  //  type is int              (2)
  decltype(a->x)   x3;  //  type is double           (3)
  decltype((a->x)) x4;  //  type is const double&    (4) 

As shown by these, decltype is not affected by the limitations of the traditional __typeof__ with respect to reference types. See cases (1) and (4), which show that such types are handled in a consistent way. It is, as such, fully integrated into the modern C++11 type system.

More complex expressions are possible. For example:

  int    i;
  float  f;
  double d;
  
  typedef decltype(i + f)  type1;  // float
  typedef decltype(f + d)  type2;  // double
  typedef decltype(f < d)  type3;  // bool

Decltype turns out to be very useful with templates in the context of generic programming, when the same generic function or class can be instantiated for different types. Via decltype the code can easily query the type of generic expressions, for example:

  template<typename T, typename U>
    void
    foo(T t, U u)
    {
       // ...

       typedef decltype(t * u) ptype;

       // use ptype...
    }

The second part of this tidbit will present more possibilities that decltype enables.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

C++ enthusiasts only, please! ;)

Search

Categories
Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today