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

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 (37)

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 (29)

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 (35)

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