Tag Archives: c++

Codexpert – 2016 Articles Summary

C++ Programming Language

Microsoft Libraries

Visual C++

See also

Guidelines Support Library Review: string_span<T>

In a previous post I have introduced the span<T> type from the Guidelines Support Library. This is a non-owning range of contiguous memory recommended to be used instead of pointers (and size counter) or standard containers (such as vector or array). span<T> can be used with strings, but the Guidelines Support Library provides a different span implementation for various types of strings. These string span types are available in the string_span.h header.

String span types

There are several string span types defined in the string_span.h header:

  • basic_string_span: the actual implementation for a string span on which several type aliases are available:
    • string_span: a string span of char
    • cstring_span: a string span of const char
    • wstring_span: a string span of wchar_t
    • cwstring_span: a string span of const wchar_t

  • basic_zstring_span: a null terminated string span used for converting null terminated spans to legacy strings; it has several type aliases available:
    • zstring_span: a null terminated string span of char
    • czstring_span: a null terminated string span of const char
    • wzstring_span: a null terminated string span of wchar_t
    • cwzstring_span: a null terminated string span of const wchar_t

These look like a lot of classes with similar names, but the names are self explanatory (terminology is c=const, w=wide, z=null-terminated):

  • string: a string of char
  • cstring: a string of const char
  • wstring: a string of wchar_t
  • cwstring: a string of const wchar_t
  • zstring: a (zero) null-terminated string of char
  • czstring: a null-terminated string of const char
  • wzstring: a null-terminated string of wchar_t
  • cwzstring: a null-terminated string of const wchar_t

Creating a string_span

A string_span can be created in many ways, including:

(Note that in all following examples the string span is the range { L'H',L'e',L'l',L'l',L'o',L' ',L'w',L'o',L'r',L'l',L'd' } of either char or wchar_t.)

  • from a literal string

  • from a pointer

  • from a standard string

  • from an array

  • from a vector

Converting to string

To convert a string span into a string you can use the to_string() function.

Size of a string_span

Unlike span<T>, a string_span<T> only have one dimension, so the rank() method does not make make sense and is not available. However, a string span has several methods for the size of the span:

  • size() and length(): return the number of elements of the span
  • size_bytes() and length_bytes(): return the number of bytes of the span

Subspans

It is possible to create subspans from a string_span. There are several functions that do that:

  • first(): returns the sub-span with the first N elements from the original string_span
  • last(): returns the sub-span with the last N elements from the original string_span
  • subspan(): returns the sub-span within the specified range (first and last positions) of the original string_span.

Comparisons

You can use the comparison operators (==, !=, <, <=, >, >=) with two string spans. Just like in the case of span<T>, equality is checked with std::equal (two ranges are equal if every element in the first range is equal to the element corresponding to the same position in the second range) and less/greater is checked with std::lexicographical_compare() (one range is less than another if the first mismatch element in the first range is less than the element on the same position in the second range).

Element access

It is possible to access the content of a string_span either with iterators or indexes.

Guidelines Support Library Review: span<T>

The Guidelines Support Library is a Microsoft implementation of some of the types and functions described in the C++ Core Guidelines maintained by the Standard C++ Foundation. Among the types provided by the GSL is span<T> formerly known as array_view<T>. This article is an introduction to this type.

span<T> is a non-owning range of contiguous memory recommended to be used instead of pointers (and size counter) or standard containers (such as std::vector or std::array).

Suppose you want to create a function that displays the content of a container. Such a function could look like this:

This will work with vectors, but not with arrays or lists. So then you need overloads in order to support other containers.

But what if you now what to display the content of an int[] or an int*?

The span<T> type is intended as a uniform interface over arrays, pointers and standard containers that can be used as a replacement of these types. It does not store a copy of the original data, only a pointer to data and counters.

The following helper functions are used in the samples below:

Creating a span

A span can be created in many ways, including:

  • from a single value (variable, not a literal)

  • from a pointer and number of elements

  • from a begin and end pointer

  • from a C-like array

  • from a dynamic array

  • from a standard container with contiguous memory layout such as array, vector or string

  • using the gsl::as_span() function:

Notice that it is not possible to create a span from an initializer_list because an initializer list is a temporary object and a span is a non-owning container, it does not make a copy of the data, and therefore it can end up containing dangling references to temporary data. For a detailed discussion on the topic see this issue.

Size of a span

A span can have zero, one or more dimensions, and each dimension can have a different size (number of elements). The number of dimensions is called rank and the number of elements in a dimension is called extent. You can retrieve the rank and extent using the functions with the same name.

Subspans

It is possible to create subspans from a span. There are several functions that do that:

  • first(): returns the sub-span with the first N elements from the original span
  • last(): returns the sub-span with the last N elements from the original span
  • subspan(): returns the sub-span within the specified range (first and last positions) of the original span.

Comparisons

You can use the comparison operators (==, !=, <, <=, >, >=) with two spans. Equality is checked with std::equal (two ranges are equal if every element in the first range is equal to the element corresponding to the same position in the second range) and less/greater is checked with std::lexicographical_compare() (one range is less than another if the first mismatch element in the first range is less than the element on the same position in the second range).

Element access

It is possible to access the content of a span either with iterators or indexes.

When it comes to index access you can either index like a regular array (s[0], s[1][2], etc.) or using a special type called index.

Codexpert – 2015 Articles Summary

Microsoft Libraries and C++ Programming Language

What’s next?

We planned to continue the Direct2D/DirectWrite series but also other articles about programming with C++ using Microsoft Windows libraries like MFC, ATL, Windows API and so on.

See also

Using Lambdas in MFC Applications – Part 3: Dealing with C++ REST SDK

C++ REST SDK (also known as Casablanca) offers support for HTTP client/server, JSON, URI, asynchronous streams, WebSockets client, oAuth and PPL Tasks.
We can get C++ REST SDK from CodePlex  or use the one shipped with Visual Studio 2013.
This article gives suggestions of how to set up a Visual C++ project (particularly one that uses MFC) in order to be able to deal with Casablanca library. It also shows some simple sample code and a demo MFC project.

Set up the project for using C++ REST SDK

First, must find the location where C++ REST SDK is installed. With Visual Studio 2013 installed, I found it in the following path:
C:\Program Files (x86)\Microsoft SDKs\Cpp REST SDK for Visual Studio 2013\SDK\ which is similar to $(ExtensionSDKDirectoryRoot)\Cpp REST SDK for Visual Studio 2013\SDK.
Next, create a new MFC project or open an existing one, right click on it’s name, choose “Properties” from the context menu, then do the following:

  1. Choose All configurations in the Configuration combo box.
  2. Go to Configuration Properties / C/C++ / General and add $(ExtensionSDKDirectoryRoot)\Cpp REST SDK for Visual Studio 2013\SDK\include to Additional Include Directories list.
  3. Go to Configuration Properties / C/C++ / Command Line and add -Zm200 in Additional Options field; this is necessary to avoid C3859 compiler error when include Casablanca headers in stdafx.h.
  4. Go to Configuration Properties / Linker / General and add $(ExtensionSDKDirectoryRoot)\Cpp REST SDK for Visual Studio 2013\SDK\lib\$(PlatformTarget)\$(Configuration) to Additional Library Directories list.
  5. Go to Configuration Properties / Linker / Input and add casablanca120.lib to Additional Dependencies.
  6. Also in Configuration Properties / Linker / Input add casablanca120.dll to Delay Loaded DLLs list; this is necessary to avoid false memory leaks reported by the MFC framework;
  7. Go to Configuration Properties / Build Events / Post-Build Event and add the following command to Command Line field
     copy /Y “$(ExtensionSDKDirectoryRoot)\Cpp REST SDK for Visual Studio 2013\SDK\bin\$(PlatformTarget)\$(Configuration)\casablanca120.dll” “$(OutDir)”; this copies the necessary Casablanca DLL from its install folder in the output directory of our project.
  8. Close the project property pages dialog.
  9. In stdafx.h include all necesary Casablanca headers, e.g. http_client.h, json.h, pplxtasks.h and so on.

Now, we are ready to go on and use C++ REST SDK stuff in our own MFC application.

Notes

  • Remember that other versions of Visual Studio may install C++ REST SDK in other location!
  • May be other methods to set up the project paths, as for example by using Property Manager and/or edit .props files; I just presented one presumed simpler.
  • Ones would prefer to get C++ REST SDK from CodePlex; probably, I’ll describe this alternative in a future article.

Next is some code sample. You can notice it uses lambda expressions and for that reason I included this article in Using Lambdas in MFC Applications series.

Using lambdas and C++ REST SDK with MFC – sample code

This sample sends a JSON structure in URI query part to a site which gives in response also a JSON which says if the sent one is valid or not and gives an error description if necessary.

More details about project settings and source code can be found in the attached demo project.

Using lambdas and C++ REST SDK with MFC – demo project

Download: JSON Verifier - Demo Application using Casablanca.zip (690)

JSON Verifier - Demo Application using Casablanca

JSON Verifier – Demo Application using Casablanca

References and related articles

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