decltype

The decltype keyword creates a variable of the type indicated by an expression.
The following statement means “make y the same type as x,” where x is an expression:

#include <iostream>

int main()
{
 int iX;

 decltype(iX)y; //set type of iX for y

 std::cout << "type of y: " << typeid(y).name() << '\n';

 return 0;
}

Output:
decltype1

Let’s show another example:

  • Set to the ‘XY’  same type as dX*iY
  • Set to the ‘ptrdX’ same type as &dX, i.e. double*
#include <iostream>

int main()
{
 double dX;
 int    iY;

 decltype(dX*iY)  XY;
 decltype(&dX) ptrdX;

 std::cout << "type of XY:"   << typeid(XY).name()   << '\n';
 std::cout << "type of ptrdX:"<< typeid(ptrdX).name()<< '\n';

 return 0;
}

Output:
decltype2

It’s maybe  particularly useful in a generic programming (in template definitions), when the type may not be determined until a specific instantiation is made:

template<typename T1, typename T2)
void Foo(T1 t1, T2 t2)
{
   decltype(T1*T1) t1_t2;
   ...
}

The workings of decltype are more complicated than those of auto, and the resulting
types can be references and can be const-qualified, depending on the expressions used.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s