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

MFC Support for Direct2D – Part 2

A previous article shows how to use D2D MFC classes for easily make a simple image viewer. As said there, it can be made even easier.

Enabling D2D support in MFC

  1. In the WM_CREATE message handler call CWnd::EnableD2DSupport.
  2. In the overridden CView::OnUpdate load the bitmap from the current document’s file.
  3. Map AFX_WM_DRAW2D registered message which is sent by the framework if D2D support is enabled. Perform all Direct2D painting in the AFX_WM_DRAW2D message handler.

That’s all. No need to create a render target, resize it, recreating it when nesessary, calling BeginDraw, EndDraw, etc. All is done in the MFC framework if D2D support is enabled for a window.

Demo project

Download: Image VIewer - Enabling D2D Support for MFC.zip (28)

Resources and related articles

User defined literals

The C++ language defines various built-in literals (numerical, character, string, boolean and pointer) and a series of prefixes and suffixes to specify some of them. The suffix or prefix is part of the literal.

The C++11 standard introduced the possibility to create user-defined literals, that are basically built-in type literals (integer, float, char or string) followed by a used-defined suffix. User-defined literals enable the creation of new objects based on the built-in literal value and the applied user-defined suffix.

A bit of theory

A user-defined literal is treated as a call to a literal operator or a literal operator template. User-defined literals have two forms:

  • raw: a sequence of characters; the literal 0xBAD is in raw form is ‘0’, ‘x’, ‘B’, ‘A’, ‘D’
  • cooked: is the compiler interpreted type of the sequence of characters; the literal 0xBAD is the integer 2898 in cooked form.

User-defined literals:

  • support only the suffix form; defining prefixes is not possible;
  • begin with a underscore (‘_’); all suffixes that begin with any other character except underscore are reserved by the standard;
  • can be extended in both raw and cooked form; the exception is represented by strings that can only be extended in the cooked form

Cooked literals

The literal operator called for a cooked literal has following form:

Only several input types are allowed:

  • for integral literals (decimal, octal, hexadecimal or binary) the type is unsigned long long (the reason for unsigned is that the sign is not part of a numeric literal, but is in fact a unary operator applied to the numerical value).
  • for floating point types the type is long double:
  • for characters the type is char, wchar_t, char16_t or char32_t:
  • for strings the type is char const *, wchar_t const *, char16_t const * or char32_t const *:

Raw literals

Raw literals are supported only for integral and floating point types. The literal operator called for a cooked literal has following form (notice that the operator does not take a second parameter to indicate the size, the string is null-terminated):

Parsing this array of characters may involve loops, variable declaration, function calls, etc. As a result this form of the literal operator cannot be constexpr, which means it cannot be evaluated at compile time.

An alternative way of processing raw literals is with a literal operator variadic template. The purpose of a variadic template literal operator is to make the literal transformation at compile time. The form of the literal operator template is:

A bit of practice

Let’s take the following example where we declare a buffer of 4 KB.

This is identical to the following declaration (you’d usually expect)

It is made possible by the existence of a literal operator with the following form:

If the literal operator was not a constexpr then the compiler would trigger an error when declaring the buffer variable, because the size of the array must be known at compile time. You’d still be able to use the user-defined literal but in runtime contexts, such as sizing a vector.

In the next example we define a user-defined literal for expressing temperatures in Fahrenheit degrees. Supposing the Celsius degrees are the norm, we can write sometime like this:

and use it like in the following example:

The return type of the literal operator can be any type; it does not have to be a built-in type like in the previous examples. Given the following hierarchy of classes we can create user-defined literals that enable the creation of developer and quality assurer objects:

In the next example we want to express latitudes, such as 66°33’39”N (the Arctic Circle). (Notice that the following types and just some simple implementations for demo purposes only).

With this in place we can create objects like this:

Values like Latitude(66, 0, 0) are not very intuitive. Even though it’s more verbose it may be more desirable to be able to create objects like this:

That is possible if we define deg(), min() and sec() as following:

User-defined literals makes is more simple and more natural. By transforming the above functions into literal operators we can simplify the syntax.

As a result we can now create latitudes like this:

It should be very simple to develop this to support longitudes. You don’t have to add more literal operators, just the Longitude type and the appropriate overloaded operators for it.

Standard user-defined literals

C++14 defines several literal operators:

  • operator""if, operator""i and operator""il for creating a std::complex value

  • operator""h, operator""min, operator""s, operator""ms, operator""us, operator""ns for creating a std::chrono::duration value

    This is equivalent to the following (longer) form in C++11:

  • operator""s for converting a character array literal to a std::basic_string

Notice that all these literal operators are defined in separate namespaces that you have to use.

References

Compiler support

User defined literals are supported by major compilers starting with the following version:

See also:

MFC Support for Direct2D – Part 1

A few time ago, I begun writing a series of wrapper classes to make easier the using of Direct2D interfaces. Meanwhile, I discovered that MFC Library, beginning with Visual Studio 2010 SP1, offers an excelent built-in support. That’s pretty cool!
So, let’s use Direct2D (D2D) MFC classes for making a simple image viewer.

Image viewer using Direct2D MFC classes

  1. In the view’s class definition, add data members for render target and Direct2D bitmap.
  2. Create the render target in the view’s WM_CREATE message handler.
  3. In the view’s WM_SIZE message handler resize the render target.
  4. Override CView::OnUpdate and load the bitmap from the current document’s file.
  5. Prevent painintg in WM_ERASEBKGND message handler.
  6. Finally, override CView::OnDraw and draw the bitmap.

Notes

  • CD2DBitmap::Create uses WIC (Windows Imaging Component) interfaces, so beside common image formats like BMP, JPEG, GIF, PNG, and TIFF, can deal also with any other image format for which a WIC-compliant decoder is installed in system.
  • Next article will show an even easier mode of using Direct2D MFC support.

Demo project

Download: Image Viewer - Using Direct2D MFC Classes.zip (27)

Using Direct2D MFC Classes - Demo Project

Using Direct2D MFC Classes – Demo Project

Resources and related articles

Tree-View Control – TVS_EX_RICHTOOLTIP style

Windows Vista introduced a buch of extended styles for tree-view control (SysTreeView32). Among them, there is TVS_EX_RICHTOOLTIP style which is described in MSDN documentation as follows: “Allow rich tooltips in the tree view (custom drawn with icon and text)”. This article shows a little bit more about how to set and which is the effect of using this extended style.

How to set and remove TVS_EX_RICHTOOLTIP style

Like the other tree-view extended styles, TVS_EX_RICHTOOLTIP can be set or removed as follows:

Sending TVM_SETEXTENDEDSTYLE message

Using TreeView_SetExtendedStyle macro

Calling CTreeCtrl::SetExtendedStyle (MFC)

Further, let’s use the above code and see what’s happen.

The effect of TVS_EX_RICHTOOLTIP style

By default, if the mouse pointer hovers a partially visible tree item, a tootip containing the item’s text is shown.

Tree item tooltip - TVS_EX_RICHTOOLTIP not set

Tree item tooltip – TVS_EX_RICHTOOLTIP not set

If the TVS_EX_RICHTOOLTIP style is set, then the tooltip displays the item’s icon in addition to the item’s text.

Tree item tooltip - TVS_EX_RICHTOOLTIP set

Tree item tooltip – TVS_EX_RICHTOOLTIP set

Note that TVS_EX_RICHTOOLTIP has no effect if TVS_INFOTIP style is set. In this case, the tooltip shows the text provided in TVN_GETINFOTIP notification handler and no icon. So far, that’s all I found about it. If somebody can reveal more, please do not hesitate to leave a reply!

Downloads

Demo project (Visual Studio 2013) – TVS_EX_RICHTOOLTIP_Demo.zip (30)

Resources

How to Get Visual C++ Sample Projects

Latest versions of Visual Studio come with few or no source code project samples. However, there are hundreds available on Microsoft sites. Here is how to get them.

Install samples using Visual Studio 2012 or 2013

For getting samples from Visual Studio IDE, follow next steps:

  1. On the Help menu, click Samples.
    Get Visual C++ samples - step 1

    Get Visual C++ samples – step 1

    If you have Visual Studio 2012 or Visual Studio 2013, the New Project dialog is open.

  2. Expand left-pane tree to the desired category, e.g Visual C++ / Desktop / Win32 / Graphics and 3D, select a sample project from the list, them click the OK button.

    Get Visual C++ samples - step 2

    Get Visual C++ samples – step 2

  3. In the Download and Install dialog, click on Install button.

    Get Visual C++ samples - step 3

    Get Visual C++ samples – step 3

Now, the sample project is added to the installed samples list, which are available each time you want to have a look inside.

Installed samples

Installed samples

Additionally, each time when open an installed sample project, Visual Studio shows a page containing the sample description, a link to download page, plus links to useful resources and tutorials. That’s pretty cool but notice that Visual Studio gets only the samples written for its own version. To get access to all samples, see the next method.

Download Visual C++ samples from MSDN Developer Code Samples

Here is the magic link: http://code.msdn.microsoft.com/
Click it here or type in a browser and get the main Developer Code Samples page. You can filter the articles according to your interests (programming language: C++, platform: Desktop and so on). Moreover, you can type a keyword to refine the filter (e.g. Direct2D) like in the below picture.

Developer Code Samples page

Developer Code Samples page

All to do next is to click on desired link and download.

Notes

  • If click Help / Samples in a version prior to 2012, Viusal Studio shows a page containing a link to Visual Studio Samples site.
    Visual Studio 2010 Samples

    Visual Studio 2010 Samples

     

Resources

Downloads

Five new algorithms to C++11 that you should know about

C++11 added a bunch of new general purpose algorithms to the <algorithm> header. In this article we will look at five of them that C++ developers should know about.

all_of, any_of and none_of

These are actually three, not just a single algorithm, all_of, any_of, none_of, but they are very similar. They check if the supplied unary predicate return true for all, any or no element in a range.

Here are several examples:

is_sorted and is_sorted_until

The first algorithm, is_sorted, checks if the elements of the range are sorted ascending. There are two overloads of the function, the first uses operator< and the second takes a comparison function (that return true if the first element is less than the second) and uses that for comparing the elements in the range.

The second algorithm, is_sorted_until, is similar in that it checks that the elements of a range are sorted ascending. However, the function does not return a boolean value, but an iterator to the upper bound of the largest sorted sub-range (starting at the beginning of the examined range), i.e. the next beyond the last sorted element. There are two overloads, the first uses operator< and the second takes a comparison function, just like is_sorted does.

The output for this sample is:

is_partitioned

Algorithm is_partitioned checks whether a range is partitioned, i.e. sorted according to the supplied unary predicate so that all elements that satisfy the predicate come before all elements that do not satisfy the predicate. The function returns true if the range is empty.

is_permutation

Algorithm is_permutation determines whether a range is a permutation of another range. There are two overloads, the first uses operator== to compare the elements of the two ranges and the second takes a binary predicate (that returns true if two elements are equal).

minmax_element

The minmax_element algorithm finds both the minimum and the maximum element in a range and returns a pair of iterators to these elements. It is important to note that:

  • if the range is empty it returns std::make_pair(first, first)
  • if there is more than one element equal to the minimum value it returns an iterator to the first of these elements
  • if there is more than one element equal to the maximum value it returns an iterator to the last of these elements

There are two overloads, the first uses operator< to compare elements and the second uses a provided comparison function.

The output is: