Concepts Lite: Constraining Templates with Predicates -- Andrew Sutton, Bjarne Stroustrup

During the C++11 standards development cycle, much work was done on a feature called "concepts" which aimed at providing systematic constraints on templates. Concepts was deferred from C++11 for lack of time to complete it, but work has continued.

In January 2012, the results of a major "concepts summit" were published as a 133-page report titled "A Concept Design for the STL" (WG21 paper N3351).

Now, a draft of new paper is available proposing a very useful subset of concepts, dubbed "Concepts Lite", for near-term consideration including at the spring ISO C++ meeting in Bristol, UK, this April. For example, imagine writing this template:

template<Sortable Cont>
void sort(Cont& container);

and when you call it like this:

list<int> lst = ...;   // oops, bidirectional iterators
sort(lst);             // today, results in very long "template spew" error message

getting this short and non-cryptic error message:

error: no matching function for call to ‘sort(list<int>&)’
   sort(l);
         ^
note: candidate is:
note: template<Sortable T> void sort(T)
   void sort(T t) { }
        ^
note: template constraints not satisfied because
note:   'T' is not a/an 'Sortable' type [with T = list<int>] since
note:     'declval<T>()[n]' is not valid syntax

That's an actual error message from the prototype GCC implementation linked below.

We're very excited about this feature and its continued progress. Here are links to the draft of the new paper:

Concepts Lite: Constraining Templates with Predicates (PDF) (Google Docs)

From the Introduction:

In this paper, we introduce template constraints (a.k.a., “concepts lite”), an extension of C++ that allows the use of predicates to constrain template arguments. The proposed feature is minimal, principled, and uncomplicated. Template constraints are applied to enforce the correctness of template use, not the correctness of template definitions. The design of these features is intended to support easy and incremental adoption by users. More precisely, constraints:

  • allow programmers to directly state the requirements of a set of template arguments as part of a template’s interface,
  • support function overloading and class template specialization based on constraints,
  • fundamentally improve diagnostics by checking template arguments in terms of stated intent at the point of use, and
  • do all of this without any runtime overhead or longer compilation times.

This work is implemented as a branch of GCC-4.8 and is available for download at http://concepts.axiomatics.org/~ans/. The implementation includes a compiler and a modified standard library that includes constraints. Note that, as of the time of writing, all major features described in this report have been implemented.

Related links:

New forum active: SG8 (Concepts)

A new publicly readable committee forum is now available on the Forums page:

SG8 : Concepts

Near-term focus is on a convergence between the static if proposals and the parameter-type-constraints subset of concepts.

Note that this forum is for standardization of a new feature; do not expect the features mentioned in this forum to be available yet in your own compiler. However, if you're interested in seeing the shape of the feature as it advances to being approved by the committee likely in the near future, this forum is for you.

For information about this and other SGs, see also:

 

Quick Q: When should I use std::function vs. make my function a template? -- StackOverflow

To accept a functor as a parameter, when should you:

  • accept a std::function, which adds an indirection, vs.
  • make your function a template<class Func> and accept a Func, which can bind directly to whatever is passed?

std::function vs template

Thanks to C++11 we received the std::function family of functor wrappers. Unfortunately, I keep hearing [...] that they are horribly slow. [... Is the right recommendation] that functions can be used as de facto standard of passing functors, and in places where high performance is expected templates should be used?

Quick Q: How do I move an expensive object into a map? -- StackOverflow

Quick A: Using the form of insert that takes an rvalue and passing a temporary or a std::move'd object, or calling emplace.

Moving an object into a map

The problem with this is that the huge objects will be copied into the maps

 

Huge huge1(some,args);
Huge huge2(some,args);

std::map<int,Huge> map1;
std::map<Huge,int> map2;

map1.insert({0,huge1});
map2.insert({huge2,0});

how can I guarantee a move? Will this work or is there more to it?

map1.insert({0,std::move(huge1)});
map2.insert({std::move(huge2),0});

Quick Q: Is the safe-bool idiom obsolete in C++11? -- StackOverflow

Quick A: Yes. Another way that modern C++ is safer and simpler.

(If you don't know what the safe-bool idiom is, don't worry. It's  a workaround that's now obsolete.)

Xeo asked:

Is the safe-bool idiom obsolete in C++11?

This answer of @R. Martinho Fernandes shows, that the safe-bool idiom is apperently deprecated in C++11, as it can be replaced by a simple

explicit operator bool() const;

... Is our assumption in the title correct? I hope we didn't overlook any potential drawbacks.

Preconditions, Part 2 -- Andrzej KrzemieĊ„ski

Andrzej continues this month with more interesting thoughts on preconditions.

Preconditions, Part 2

by Andrzej Krzemieński

In this post I will continue sharing my thoughts on preconditions. It will cover some philosophy behind the concept of preconditions (and bugs), and investigate the possibility of employing the compiler to verify some preconditions. Many people provided a useful feedback on my previous post. I will also try to incorporate it into this post.

Note that this article diverges from recommended practice in one way... it hints at the idea of throwing exceptions to report precondition violations. Instead, per C++ Coding Standards and other established guidance, prefer to use assertions to check preconditions: precondition violations are just bugs in the caller's code that should be caught at test time, assertions cause no overhead in production, and assertions fire immediately at the line of code that contains the bug without losing the call stack and other local context. Using assertions is still considered to be a best practice.

Learning Modern C++: An Interview with Barbara Moo -- Jeff Martin

Now at InfoQ:

Learning Modern C++: An Interview with Barbara Moo

by Jeff Martin

The popularity of C++ has varied throughout the years since its introduction in the 1980s.  The rise of managed languages like Java and C# along with the emergence of scripting languages like JavaScript, Python, and Ruby has affected C++'s adoption.  Yet many supporters like C++ for the control, raw power, and speed that it offers.  C++11 promises to bring that power to programmers in a more efficient manner, and the changes it introduces illustrate how much the language has grown in the past 30 years.  Programmers looking to learn about C++11 or perhaps sample C++ for the first time would do well to try C++ Primer, 5th Edition by Stanley B. Lippman, Josée Lajoie, and Barbara E. Moo.  InfoQ had the opportunity to speak with Ms. Moo about her new book and the C++ language as a whole.

Continue reading...

Open and Efficient Type Switch for C++ -- Solodkyy, Dos Reis, and Stroustrup

Here's a recent highlight from the pre-Portland mailing that you might have missed:

Open and Efficient Type Switch for C++

Yuriy Solodkyy, Gabriel Dos Reis, Bjarne Stroustrup

... we implement a type switch construct as an ISO C++11 library, called Mach7. This library-only implementation provides concise notation and outperforms the visitor design pattern. ... For closed sets of types, its performance roughly equals equivalent code in functional languages, such as OCaml and Haskell.

C++ is a powerful library-building language. Whenever possible, we prefer to add new functionality as a library rather than in the language. This is an excellent example of where a C++ library-only solution can get equivalent performance to the language support included in some popular functional languages.

What's new in C++11? -- KDAB

KDAB is now offering three-day training courses in C++11.

What’s New in C++11?

This three-day training teaches everything about the new C++ standard, C++11.

Course description

Table of contents (PDF)

C++11 will become more and more important in the C++ ecosystem, eventually becoming the most prevalent version. Every professional developer should invest in learning the new language version and try introducing its benefits into projects. And for good reasons: C++11 brings a large range of new features that makes development safer, faster, easier and more fun. Once you have tried features like lambda functions, range-based for loops, the auto keyword and the new initialization syntax, you won't want to go back. In addition to that, many more advanced features like variadic templates, rvalue reference and of course the new standard library additions like multithreading classes, smart pointers, regular expressions and new containers and algorithms complete the picture.

During the training day at Qt DevDays 2012 in Berlin, KDAB engineer Marc Mutz, presented some the most important C++11 features using parts of the material from this course. This was very well attended, receiving positive feedback.

Our full training lasts for three days and covers a wide range of topics, it goes in-depth and provides time to show C++11 examples as well as allowing participants to go hands-on and trying out C++11 themselves in exercise projects.

See the course description for more details about the content.

To view our schedule and to book your place for our next C++11 trainings go to: www.kdab.com/schedule/

atomic Weapons: The C++ Memory Model and Modern Hardware -- Herb Sutter

Herb Sutter's biggest and deepest talk at C++ and Beyond 2012 is now online:

atomic<> Weapons: The C++ Memory Model and Modern Hardware

by Herb Sutter

This session in one word: Deep.

It's a session that includes topics I've publicly said for years is Stuff You Shouldn't Need To Know and I Just Won't Teach, but it's becoming achingly clear that people do need to know about it. Achingly, heartbreakingly clear, because some hardware incents you to pull out the big guns to achieve top performance, and C++ programmers just are so addicted to full performance that they'll reach for the big red levers with the flashing warning lights. Since we can't keep people from pulling the big red levers, we'd better document the A to Z of what the levers actually do, so that people don't SCRAM unless they really, really, really meant to.

Topics Covered:

  • The facts: The C++11 memory model and what it requires you to do to make sure your code is correct and stays correct. We'll include clear answers to several FAQs: "how do the compiler and hardware cooperate to remember how to respect these rules?", "what is a race condition?", and the ageless one-hand-clapping question "how is a race condition like a debugger?"
  • The tools: The deep interrelationships and fundamental tradeoffs among mutexes, atomics, and fences/barriers. I'll try to convince you why standalone memory barriers are bad, and why barriers should always be associated with a specific load or store.
  • The unspeakables: I'll grudgingly and reluctantly talk about the Thing I Said I'd Never Teach That Programmers Should Never Need To Now: relaxed atomics. Don't use them! If you can avoid it. But here's what you need to know, even though it would be nice if you didn't need to know it.
  • The rapidly-changing hardware reality: How locks and atomics map to hardware instructions on ARM and x86/x64, and throw in POWER and Itanium for good measure – and I'll cover how and why the answers are actually different last year and this year, and how they will likely be different again a few years from now. We'll cover how the latest CPU and GPU hardware memory models are rapidly evolving, and how this directly affects C++ programmers.

Herb adds on his blog:

Note: This is about the basic structure and tools, not how to write lock-free algorithms using atomics. That next-level topic may be on deck for this year’s C++ and Beyond in December, we’ll see...