Binary literals and digit separators

The C++14 standard provides two new small features to the language: binary literals and digit separators. They are already available in Clang 3.4 and GCC 4.9 and now Visual Studio 2015 RC has implemented them. They may not be something you can’t live without, but sometimes it’s convenient to have them. Let’s have a look.

In C++ it was possible to input integer literals in several bases: decimal, hexadecimal and octal. However, the binary base has been omitted (though other languages supported that). With C++14 binary is also supported and binary literals are introduced with the prefix 0b or 0B.

Binary literals can be used anywhere integral literals are expected.

What if you had to write large literals such as 0b101111000110000101001110, which is the binary representation of decimal 12345678? Sometimes it is convenient to separate groups of digits for more human readability.

C++14 defines the single quotation mark (') as a digit separator in integral and floating point literals. So the binary literal 0b101111000110000101001110 can be expressed in several ways:

or maybe in hexadecimal:

The position of the single quotation marks in the integral or floating point literals is irrelevant, they are simply ignored when determining the value of the literal. All the following are equivalent (but probably only the first and the last make sense).

Using Lambdas in MFC Applications – Part 2: Replacing Callback Functions

According to C++11 Standard, stateless lambdas, i.e. having an empty lambda introducer or capture no variables, are implicitly convertible to function pointers. Visual C++ in Visual Studio 2012 and newer, supports this feature. Moreover, in Visual C++ stateless lambdas are convertible to function pointers with arbitrary calling conventions. This is great if have to deal with Win32 API functions, most of them using __stdcall calling convention.
Let’s begin with two simple examples of enumerating top-level windows, one by using a callback function and the other by using a lambda expression.

Enumerate windows using “classic” callback functions

Usually, for that purpose we declare and implement as callback, a static member function having the signature required by EnumWindows in its first argument.

Notes

  • CALLBACK is defined in Windows SDK as __stdcall.

Enumerate windows using lambda expressions

The same result can be achieved by using a lambda expression. This is somehow simpler because does not require to declare and define a static member function.

Notes

  • as stated in the introduction, there is not necessary to explicitly convert the lambda expression to the function pointer required by EnumWindowsProc (WNDENUMPROC);
  • as stated in the introduction, there is not possible to capture neither local variables, nor this pointer; luckily, like in many other WinAPI callbacks, we can pass the necessary stuff in a parameter of type LPARAM or LPVOID.

Using nested lambda expressions

Let’s say we want to enumerate the top-level windows in a worker thread. We can write something like this:

We have passed lambdas both for callback parameter of AfxBeginThread and EnumWindows. EnumWindows is called in the first lambda body and takes a lambda as well.
This compiles with no problem in x64 builds, but may give a conversion error for the inner lambda in Win32 ones. That’s a little glitch which AFAIK has been fixed in Visual Studio 2015.
However, to be sure it compiles also in Visual Studio 2012/2013 – Win32 builds, we can simply cast explicitly the inner lambda.

Notes

  • x64 builds has no __stdcall calling convention; __stdcall keyword is still accepted but simply ignored by the compiler.
  • of course, we can use lambda expressions in the same way also in ATL applications or C++ programs that use plain WinAPI.

Resources and related articles

Using Lambdas in MFC Applications – Part 1: Sorting Arrays

Beginning with Visual Studio 2010 which supports lambda expressions introduced by C++11 standard, you can handily sort an MFC array like in the following example:

Sorting CStringArray by using a lambda expression

Of course, you can write similar code for other types of MFC arrays like CArray, CUIntArray, and so on.
But also you can easily write a kind of “generic lambda” in order to sort any type of MFC arrays.

Using decltype to sort any type of MFC array

That’s pretty cool… However would be nice to be possible to get rid of “wordy” constructions like “decltype(*arr.GetData())” in the lambda’s formal parameters list. Good news! There is a proposal for next C++ standards: using auto type-specifier in order to make generic lambda expressions (which accept any type of arguments). And that is already supported in Visual Studio 2015.

Using generic (polymorphic) lambda expressions

Notes

  • Some people may claim that using MFC collection classes is obsolete and must use STL containers instead. That’s an old subject of arguing but it’s not in scope of this short article.
    It simply presents how to sort MFC arrays by using lambda expressions.

References and related articles

Codexpert – 2014 Articles Summary

Microsoft Libraries

C++ Language

Windows Tips

See also

How to Check the Windows Version

Let’s say we have to check if our application is running under Windows 8.1 or newer. A “classic” way, often found in legacy code, is to call GetVersion or GetVersionEx.

Using GetVersion

Using GetVersionEx

However, if running under Windows 8.1 the above functions may return FALSE.
Moreover, compiling in Visual Studio 2013 Update 3 or newer, we can get warnings or even errors if SDL checks compiler option (/sdl) is set.

That’s because with the release of Windows 8.1, the behavior of the GetVersion and GetVersionEx has changed. Additionally, the MSDN documentation says that GetVersion and GetVersionEx may be altered or unavailable for releases after Windows 8.1. Instead, we still can use VerifyVersionInfo.

Using VerifyVersionInfo

Much easier and recommended in MSDN documentation, is to use Version Helper functions defined by VersionHelpers.h, which is included in the Windows 8.1 SDK. In our case we can simply call IsWindows8Point1OrGreater.

Using Version Helper functions

Notes

  • We can still use the deprecated GetVersion and GetVersionEx returning correct version under Windows 8.1 by setting Windows 8.1 target in the manifest (see Targeting your application for Windows 8.1 topic in MSDN). However, using Version Helper functions is easier and probably more reliable for the future versions.

Resources and related articles

C++11: Let’s Write a “Hello Lambda!”

A lambda expression (aka lambda function), introduced in C++11 standard, is a simplified notation for defining an anonymous function object. However, its syntax and using may look weird for many people so let’s try to make a simple program to accommodate with it.

Let’s describe each part, in order.

The parts of a lambda expression

  • [] is the lambda introducer that may be empty or may contain a capture list; this part is mandatory for defining a lambda expression;
  • () is a formal parameters list; if it takes no parameters and no specifier like mutable or noexcept has been used, this part is optional;
  • mutable is an optional specifier which indicates that the copies of variables captured by value can be modified inside the lambda body;
  • throw() (or noexcept) is an exception specifier which is also optional;
  • ->void is the return type; it is optional if the compiler can deduce the return type;
  • { std::cout << "Hello Lambda!"; } is the body specifying the code to be executed.
  • finally, we have in our example a function-call operator, (), which is not a part of lambda expression.

Getting rid of optional parts, we can make our program simpler, as follows:

Further, let’s take a little deeper look in the lambda introducer part.

The lambda introducer and the capture list

As already said before, the lambda introducer that may be empty or may contain a capture list. An empty lambda introducer means “no capture is made”. Otherwise, the local variables from the place where lambda is defined can be “captured” (i.e. used in the lambda body) as follows:

  • [=] all local variables are implicitly accessed by value;
  • [&] all local variables are implicitly accessed by reference;
  • [capture_list] a list of variable names to be captured (explicit capture); if a variable name is preceded by & then it is captured by reference; otherwise, it is captured by value;
  • [=, capture_list] all variables which are not in the capture_list are captured by value;
  • [&, capture_list] all variables which are not in the capture_list are captured by reference;

Note that variables captured by value cannot be modified inside the lambda body, except case the mutable specifier has been used.
Now, let’s make our program a little bit more complicated to illustrate the using of capture list and other lambda expression parts.

Notes

  • This article presented just trivial examples, introducing lambda expressions as simple as possible. You can find tens of articles and examples presenting lambdas deeper. See also references and related articles, below.
  • std::function is an STL class that wraps callable objects like functions, lambda expressions and so on.

References and related articles

C++ Gems: ref-qualifiers

VC++ 2014 is finally supporting ref-qualifiers, maybe a lesser know feature in C++11 that goes hand in hand with rvalue references. In this post I will explain what ref-qualifiers are and why they are important.

But before talking about ref-qualifiers let’s talk about the well known cv-qualifiers.

cv-qualifiers

Let’s take the following example of a type foo that has two overloaded methods, one const and one not const.

The following code prints either “test” or “test const” depending on whether the object function test() is called on is const or not.

Notice that the const/volatile specification is not a constrain on the function, but on the implied this parameter. A const function can freely modify state or call non-const methods, but not state or non-const methods that belong to the object referred by this.

Let’s consider a second example where he have a Widget contained within a bar. The bar has methods to return the internal state. If the object is const, the overload resolution picks the const method, if it is non-const it picks the non-const method.

The problem with this code is that in all cases the Widget was copied even though in the last example the Widget owner was an rvalue reference and the object could have been moved.

To fix this problem we can add a new method that returns an rvalue reference. However, the problem now is that we cannot have two overloaded methods, one that returns a lvalue reference and one that returns an rvalue reference. So the best we could do is this:

This fixed the 3rd case with the rvalue reference, but it broke the first object. After calling b1.data() the Widget from b1 was moved to w1.

What’s the solution?

Enter ref-qualifiers

ref-qualifiers are a way to help the compiler decide which function to call when the object is an lvalue or an rvalue. Since the object is passed as an implicit pointer type parameter to the function (pointer this) the ref-qualifiers have been also referred as “rvalue reference for *this”.

ref-qualifiers are specified with & for lvalues and && for rvalues at the end of the function signature after the cv-qualifiers.

The following code now prints “copy”, “copy”, “move” as expected.

One important thing to note is that you cannot mix ref-qualifier and non-ref-qualifier overloads. You must decided over one or another set of overloads. The following is illegal:

The ref-qualifiers help avoiding unnecessary calls/operations on rvalue references which is helpful when may involve large objects. But they are also helpful to avoid making coding mistakes. Here is an example. Consider the following type:

You can write things like this:

Probably the first example is a little bit silly, you don’t do that kind of mistake in real life, but it’s still legal code that executes, and is not right because there’s an rvalue reference on the left side of the assignment operator. The second example is definitely a much realistic example. Sometimes we just type = instead of == in conditional expressions and what the code will do is assigning 42 to temporary, instead of testing their equality.

If we changed the signature of foo’s operator= to include a ref-qualifier (as shown below) the compiler would flag immediately both examples above as errors:

VC++ 2014 now flags the following error:

error C2678: binary ‘=': no operator found which takes a left-hand operand of type ‘foo’ (or there is no acceptable conversion)

Compiler support

See also