Reply to comment

C++11: Decltype

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.

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote>
  • Lines and paragraphs break automatically.
  • You may post PHP code. You should include <?php ?> tags.
  • Web page addresses and e-mail addresses turn into links automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <cpp>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
1 + 14 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.