Author Archives: Kenny Kerr

What does it mean to be constexpr complete?

Yesterday Stephan Lavavej announced on the Visual C++ blog that their compiler would be constexpr complete for the Visual Studio 2015 build that is released to manufacturing. While that sounds exciting – and it is – I don’t think many developers really know what that means and may make certain reasonable assumptions about what is achievable at compile time. Stephan alluded to a difference between the original goals and aspirations for constexpr in the earlier C++11 standard compared to what is found in the newer C++14 standard. So what does this mean?

The original notion of a generalized constant expression is careful to limit the definition to sufficiently simple functions. That meant that such functions could not contain local variables, iteration statements, or selection statements. Such restrictions quickly became onerous and were lifted in C++14. I’m not a language lawyer so I’ll just give you an illustration. Imagine I need to count the occurrences of some character within a string. I would naturally like to express this at compile time as follows:

static_assert(Count("a % b % c % d") == 3, "fail");

With Visual Studio 2015, I need to be careful to implement the Count constexpr function to avoid using any of the aforementioned constructs. This is a reasonably simple problem so it doesn’t take a great leap of the imagination to write a simple recursive function:

constexpr unsigned Count(char const * const string)
    return *string == '\0' ? 0 : (*string == '%') + Count(string + 1);

While this is a recursive function, the recursion happens at compile time. In fact, the compiler may choose to unroll or transform the implementation to avoid recursion. From what I can tell, the Visual C++ compiler does not attempt to transform this so if I have a very large string then it will hit the compiler’s call-depth limit. Fortunately, this can be avoided with a compiler option. On the other hand, recursion is clearly not ideal and writing such contrived expressions quickly becomes error prone to say the least. The C++14 definition of constexpr functions makes it possible to write this function with more of the C++ language at my disposal:

constexpr unsigned Count(char const * string)
    unsigned count = 0;

    for (; *string != '\0'; ++string)
        count += *string == '%';

    return count;

Notice that I’m able to manually transform the recursive function with an iteration statement and use a local variable to keep track of the count. I am even able to increment the pointer. While this is a simple example and there’s nothing wrong with the recursive example above (unless I have very large strings) it sure is handy to be able to have the expressive power of C++14 constexpr functions at my fingertips.

A second dark age for C++

The first beta of the .NET Framework arrived in 2000. As I look back at the decade following its unveiling, I cannot help but think of it as the first dark age of C++. Following on the success of Java, Microsoft likewise chose to distance itself from its strong roots in C and C++. The mighty developer division embraced managed code and worked tirelessly to build incredible tooling for C#. For a time the Visual C++ team tried to play catch-up with not one but two different language extensions for the Common Language Runtime (CLR), but they quickly realized that they were the unwelcome guest at the party. Thankfully, they returned to their roots in native code and so began the C++ renaissance championed by the likes of Charles Torre and others. This eventually culminated in amazing achievements such as the Concurrency Runtime, C++11 and dramatic improvements to the Visual C++ C Runtime (CRT) and Standard Template Library.

Just over ten years following the arrival of .NET, Microsoft announced Windows 8 and the new Windows Runtime. While .NET had arguably succeeded splendidly on the server, it always had an uneasy relationship to the Windows client mainly due to poor performance and the lack of a universal UI framework. With the advent of smaller devices, the operating system group decided to remedy the client problem by returning to the proven performance of C++ and the essentials of COM. The Windows Runtime would become the universal platform for not only the ultimate XAML implementation but also the entire Windows API.

At this point, any optimistic C++ programmer would be forgiven for thinking that the dark ages have passed and good times are ahead. Unfortunately, while the operating system group has embraced C++, the developer division remains largely unchanged. The CLR was retrofitted with support for the Windows Runtime. This is beyond ironic since .NET was specifically designed as a departure from COM with an incompatible vtable model. Performance isn’t great despite the fact that the Windows Runtime does make a number of concessions for the CLR, but at least most of the heavy lifting is now done by the operating system so C# code gets a pass.

While the operating system group has embraced C++, the developer division continues to champion C# as the tool of choice and the Visual C++ team continues to focus on standards compliance and more recently cross-platform development. Little has been done to support the Windows Runtime, certainly nothing that has captured the hearts and minds of C++ developers. C++/CLI was dusted off – a language extension designed for a garbage-collected runtime – and now offers an unnecessarily complex way to work with the Windows Runtime that makes no sense for COM. C++ is a language for library developers. The library developer’s job may not be a simple one, but you certainly have the tools at your disposal to do some amazing things. So when you hit some feature that isn’t directly supported by the language, then you write a library – you don’t go and invent a new language or write a set of language extensions. Prior to C++11 you could be forgiven for thinking in that way, but not now.

Microsoft desperately needs an infusion of modern C++ for Windows. The Universal Windows Platform built on the Windows Runtime is the ideal environment for C++ to thrive. What is missing is the determination to make it happen. Modern C++ for the Windows Runtime is the jumpstart that the Windows platform needs but it cannot happen without the support of both the operating system group and the developer division.

Jim Radigan has done some incredible work bringing code written for Android and iOS apps to Windows. Now we need to bring modern C++ to Windows as well. The C++ community is stronger than ever and forging ahead with incredible innovations to the C++ language and standard libraries. Will Windows be part of this new C++ renaissance or will this be another dark age for C++ programmers on the Windows platform?

SQLite with Modern C++

My latest course, SQLite with Modern C++, is free for a limited time on Pluralsight. If you don’t yet have a Pluralsight subscription then be sure to check it out right now.


If you do have a Pluralsight subscription, be sure to check out my growing collection of courses. My next course, Windows Runtime Internals, will also be available to subscribers within a few weeks.

Modern C++ and the Universal Windows Platform

I have started publishing information about the Modern C++ project at and I hope that you’ll go and take a look to see what I’ve been up to. Subscribe here for updates or follow me on Twitter:

I recently made the case that Modern C++ for the Windows Runtime offers the productivity of C# and performance that beats even C++/CX. Surely this would be tremendously valuable to the Universal Windows Platform. And I topped it off with my biggest video demo yet of the Modern library.

1. A Classy Type System for Modern C++

2. Modern C++ as a Better Compiler

3. When Standard C++ Isn’t Enough

Video: Universal Windows Apps with Standard C++

I’m off to work on my next course for Pluralsight entitled Windows Runtime Internals, but I’ll be back to continue the work of bringing modern ISO C++ to the Windows platform.

Adding Compile-Time Type Checking to Printf

Here’s my article in the May 2015 issue of MSDN Magazine. This is the special edition of the magazine that was available at Build 2015.

Adding Compile-Time Type Checking to Printf

I explored some techniques for making printf more convenient to use with modern C++ in my March 2015 column. I showed how to transform arguments using a variadic template in order to bridge the gap between the official C++ string class and the antiquated printf function. Why bother? Well, printf is very fast, and a solution for formatted output that can take advantage of that while allowing developers to write safer, higher-level code is certainly desirable.

While this is a convenient bridge between modern C++ and the traditional printf function, it does nothing to resolve the difficulties of writing correct code using printf. printf is still printf and I’m relying on the not entirely omniscient compiler and library to sniff out any inconsistencies between conversion specifiers and the actual arguments provided by the caller.

Surely modern C++ can do better.


Modern C++ as a Better Compiler

Last week I made the case that Standard C++ offers both productivity and performance and showed how C++ can be just as concise and elegant as C# and indeed more so. But I didn’t really address performance so let’s do so now. It’s trendy today to refer to your platform or framework of choice as being native. Everyone’s native these days. Even managed code is native. It wasn’t long ago that such a statement would have been greeted with incredulity but today it seems as if the marketing folks have hijacked the word and we’re all a happy native family. But performance doesn’t lie and when it comes to native code there’s nothing quite like Standard C++.

Here’s a question for you. Can a library outperform a compiler? With all of the talk about native code generation it’s helpful to remember that modern C++ is in many ways a code generator. The C++ community is literally bursting with impressive examples where smart C++ developers are coming up with ways of programming C++ at compile time in what is often called metaprogramming or generic programming.

But how can a library outperform a compiler? Standard C++ attempts to be the best possible language in which to write very efficient libraries. While parts of the language may be complex, libraries written in C++ should be easy to use. Modern C++ for the Windows Runtime is just such a library.

But how can a library outperform a compiler?! Doesn’t a library still need to be compiled? Well let’s run a little experiment and the Windows Runtime provides a good environment in which to compare libraries and compilers. You see, the Windows Runtime defines a binary platform that’s intended to be projected into different programming languages. When you write a Windows app in C# you are using the language projection provided by the C# compiler. The same goes for JavaScript and other language projections that I’ve heard of. But when it comes to C++ it’s a different story. Standard C++ is a different kind of language. Although it offers multiple programming paradigms it has a certain bias toward systems programming. This is why it’s so popular among operating system developers. It’s also not the kind of language that can support a language projection directly via the compiler unless you go and change the C++ language itself. This is precisely what the Visual C++ compiler attempts to do with its C++/CX language extension.

But that’s not how C++ was meant to be used. If the language doesn’t provide what you need then you can write a library. There’s no need to invent a new language or change the fundamental structure of the C++ language itself. Still, because the Visual C++ compiler offers up a compiler-based implementation of a Windows Runtime language projection we can now go ahead and compare the compiler’s performance against that of a Windows Runtime language projection implemented as a library using only Standard C++.

I’ll begin with a simple Windows Runtime component that offers up a class called Sample with a single static property returning an IVectorView of strings. An IVectorView is just a read-only vector with a portable ABI that is understood by different language projections. Using Modern C++ for the Windows Runtime I’m left simply having to implement this Strings method, which represents that static Strings property within the component:

class SampleFactory : public SampleFactoryT<SampleFactory>
    IVectorView<String> Strings()
        // code goes here

Since I’m implementing this component in modern C++, I can use whatever modern or standard libraries that I’m most familiar with as a C++ developer. Let’s use a few standard containers to build a really big vector of strings:

vector<String> values;
wstring const value = L"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

for (unsigned i = 0; i != 10000000; ++i)
    values.emplace_back(value.c_str(), i % value.size() + 1);

I’m using the standard string to act as a sort of template and then I’m filling a vector of Windows Runtime strings with a range of values that look something like this:


And this will simply repeat until the vector contains ten million strings. So I have a really big collection of strings. I now need to pass it back to the caller and I can do that by simply wrapping it inside an implementation of IVectorView as follows:

return VectorView(move(values));

So my component’s static property boils down to this:

IVectorView<String> Strings()
    vector<String> values;
    // pump full of values ...
    return VectorView(move(values));

The VectorView function will create a COM object that implements the necessary interfaces such that this standard vector of strings may be transported across ABI boundaries very efficiently.

With the component implemented I can return to app development and see what this looks like from various language projections. First let’s look at C#:

var timer = new Stopwatch();
IReadOnlyList<string> strings = Sample.Strings;
long sum = 0;

foreach (string s in strings)
    sum += s.Length;

m_sum = sum;
m_elapsed = (long)timer.Elapsed.TotalMilliseconds;

I call Sample.Strings to retrieve the collection of strings and then use a C# foreach statement to iterate over the collection. The sum is just a sanity check to confirm that each implementation walked the same collection of strings. In this case I’m using the .NET Framework’s Stopwatch class to measure how long it takes to iterate over the collection.

This is a very simple and unscientific test but it should give us a good idea of how efficiently each language projection can iterate over a collection expressed in terms of Windows Runtime collection interfaces. There’s a lot of memory involved and a lot of virtual function calls. A language projection is going to have to be very careful to manage this efficiently, but I’m sure any decent compiler can figure it out.

I ran a release build of this C# version a few times and it consistently calculated a sum of 264999712 characters in around 2619 milliseconds. Now let’s take a look at C++/CX:

IVectorView<String ^> ^ strings = Sample::Strings;
long long sum = 0;
auto start = Now();

for (String ^ s : strings)
    sum += s->Length();

m_elapsed = Elapsed(start);
m_sum = sum;

In this case I’m using a pair of functions that use the operating system’s high resolution performance counter to measure milliseconds. Other than that, the samples are equivalent, the sums match, but the elapsed time is around 628 milliseconds. And finally we come to the standard C++ approach:

IVectorView<String> strings = Sample::Strings();
long long sum = 0;
auto start = Now();

for (String const & s : strings)
    sum += s.Length();

m_elapsed = Elapsed(start);
m_sum = sum;

Here again you’ll notice that the Strings property is projected as a method and it returns a vector view of strings without any hats. From a performance perspective, the ‘const &’ in the range-based for statement is purely a matter of style and convention and the omission of which would make no difference at run time. Again the sums match, but the elapsed time is even faster at 447 milliseconds!


Can a library outperform a compiler? It’s perhaps a bit of a philosophical question but it’s clear that the C++ compiler is insanely good at optimizing Standard C++. The library developer is also in the driver’s seat and is able to optimize everything from resource management, algorithms, iterators and adapters, and so much more. Clearly C# does not provide ‘native’ performance. Although C++/CX gets you a lot closer it does so by trading productivity and you lose the essence of the C++ language. I could go on to explain why C# is so much slower but the bottom line is that only Standard C++ allows you to do anything about it. And that’s the point. If you’re using C# or C++/CX you’re at the mercy of the compiler. Only Standard C++ lets you go beyond the compiler. Modern C++ for the Windows Runtime is for those of you who love C++ but also want to create Windows apps.