Chapter 5. Digging Deep on Modern C++
The power of the additional features that were introduced with the 2011 and 2014 updates comes not just from the changes, but from the way these changes integrate with classic features. This is the primary reason the update feels like a whole new language, rather than a version of classic C++ with a collection of new features bolted on.
In this chapter, we will demonstrate what that means, which requires looking at some code. Feel free to skip this chapter if your interest in C++ is not as a coder.
Type Inference: Auto and Decltype
When a language supports type inference, it is often presented as just a convenient way to not have to explicitly write out types. “The compiler already knows the type—why should the programmer have to write it out?” Indeed, this point of view is important. Oftentimes, the type is just visual clutter, as demonstrated by the definition and usage of c_v_s_iter in Example 5-1, which is written in a pre-C++11 style.
Example 5-1. Type inference: visual type clutter
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
// trivial implementation of the unix uniq utility
// read lines from stdin
// write sorted unique lines to stdout
int
main
(
int
argc
,
char
**
argv
)
{
using
std
::
vector
;
using
std
::
string
;
using
std
::
sort
;
using
std
::
unique
;
using
std
::
cin
;
using
std
::
cout
;
vector
<
string
>
lines
;
while
(
cin
)
{
lines
.
emplace_back
();
getline
(
cin
,
lines
.
back
());
};
sort
(
lines
.
begin
(),
lines
.
Get C++ Today now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.