+

very C++ programmer has had one of those days: A simple use of a template library turns into a nightmare, with pages upon pages of error messages streaming out of the compiler. Somewhere in that proverbial haystack are the clues you will need to determine exactly what went wrongan error about a missingoperator here, an incompatible type assignment therebut you know you are in for a long search through the grisly internals of the template library, or a visit from your local C++ template guru.

This article is not about C++ template error messages, but they are indicative of a far more general problem with the C++ template system. Most errors in the use of templates come from a misunderstanding between the author of the template and the user of the template. The author of the template expects the user's type to provide some specific set of operations, say, a + operator for addition and a copy assignment operator, which I'll refer to as the template requirements. When the user provides a type with the appropriate operations, i.e., the type satisfies the template requirements, everything works. However, when the user's type is missing some operations, the compiler reports the error as soon as the template tries to use that operation, which is often deep in the implementation of the template library. Thus, the template requirements are effectively a contract between the template author and user, and debugging a template error message is the act of trying to determine who broke the contractand how.

Enter: Concepts

Concepts is a language feature planned for C++0x that allows programmers to express the template requirements as part of the template’s source code. Placing requirements on a template formalizes the contract between template author and user, allowing the compiler to ensure that both parties uphold their end of the bargain. The template author is permitted to use only operations that he has required the user to provide, while the template user is allowed to supply only types that provide all of the operations that the template requires. When both parties uphold the terms of the contract, the program works; but when one party makes a mistake, the compiler produces an error message that describes the error in terms of the contract, isolating the template author from the template user and, therefore, producing shorter, simpler error messages that do not expose library internals to the user.

This article introduces the core ideas behind concepts, showing how they can be used to express the template requirements to provide correct and easy-to-use template libraries. The end of the article will illustrate some of the advanced features of concepts that make template libraries more powerful and more flexible. The intrepid reader may want to follow along using ConceptGCC, a prototype compiler implementing the concepts language feature. Template metaprogramming gurus: Please check your template tricks at the dooryou won't need them here.