decltype
is a type specifier introduced in C++11. It behaves like a function that evaluates to the type of an object at compile time. This article is helping provide some more background information necessary for the more meatier C++11 articles to come.
decltype(4.23 * 5) v = 4.23*5;
In this example, the compiler is determining for us what the type of 4.23 * 5 would be and then giving that type to v
. With some help from typeid
we can see that the type assigned by the compiler is double
.
std::cout << typeid(v).name() << std::endl; // prints "d" with gcc
When would you want to actually use this new language feature? Hard to say. There are complex examples in template metaprogramming where it can come in useful. Or in situations where you don’t know the return type of an operation. I’m having a hard time coming up with a succinct meaningful example without introducing too many other C++11 concepts all at once. Another feature of decltype is the ability to tell you what the type signature would be if the object in question had a method called on it. The syntax is rather obscure, requiring a double set of parenthesis. That is: decltype(v)
is a non-const non-reference type. decltype((v))
is a non-const reference type. decltype
will be made more useful in coming articles.