Since C++11 became available several things have changed in C++ and also the way you used to solve problems now changes. It is indeed an interesting time for C++ developers because it's time to forget old practices and embrace the new features since C++11 is truly awesome.
I want to start this blog introducing decltype, a new keyword of the language which given an expression returns its type.
For example, in C++11 you can write this:
The type of b will be derived from a, therefore it will be int. decltype accepts any expression, therefore it is also possible to write:
In this way we don't need to infer what would be the type of the expression, but we let the compiler do the job considering that it has this knowledge. Although useful, the syntax is quite cumbersome since we have to write the expression twice and this is not probably handy to use in real codes. A better way to obtain the same result is by using the auto keyword, which is also part of the new C++11 standard. With auto declaring b is as easy as follows:
The combination of auto and decltype allows the developer to take advantage of type inference information derived by the compiler. It also allows you to do more with much lesser code. An example I found myself using lately is the declaration of sets/maps which requires to explicitly provide a comparator. The common way of doing this before C++11 was basically in two ways, either by providing a function which implements the key comparator, e.g.:
Or by using a functor object as follows:
The advantage of using a functor object is that the comparator can have state. Similar behavior can be obtained using a function if static or global variables are being used.
In C++11, the same thing can be coded with less effort as follows:
We take advantage of the auto initializer to define a lambda function (which I will cover in the future) and using the decltype keyword we get its type (which it would not be trivial to write down ourselves considering that it could be implementation dependent).
This is just a basic introduction to the wonders of decltype, there is much more to unveil, however, as we say in italian... "you cannot start running if you didn't learn to walk in the first place". Indeed, decltype might seem pretty lame and not useful alone, but combined with other features of C++11 it becomes a very powerful tool. Stay tuned for more C++ love.