I’d like to know the precise yet succinct definitions of these three concepts in one place. The quality of the answer should depend on the following two points.
- Show a simple code snippet to show how and what the concept/technique is used for.
- Be simple enough to understand so that a programmer without any exposure to this area can grasp it.
Note:
There are probably many correct answers since each concept has many different facets. If there are a lot of good answers I will eventually turn the question into CW and aggregate the answers.
— Post Accept Edit —
Boost has a nice article on generic programming concepts
A concept is a set of requirements on a type. For example, you could have a concept called “RandomAccessible”, which places the requirement on a type that it implements
operator[](int)in O(1) time.As concepts were dropped from the upcoming C++ standard, they only exist intangibly in C++ as documentation. As an example, you could read SGI’s description of the Container concept.
When a type meets all the requirements of a concept, you call it a model of that concept. For example,
std::vectoris a model of the Container concept (or, equivalently,std::vector“models” Container).Finally, a policy is a unit of behaviour, which can be combined with other units of behaviour to build complex classes. For example, say you wanted to build two classes: a fixed-size array, and a dynamically-resizable array. Both these classes have a lot of shared functionality, but just differ in their storage mechanisms, and some of their functionality (e.g. you can’t call
push_backon a fixed-size array).Usage would be as follows:
Obviously this is a very crude and incomplete example, but I hope it illuminates the concept behind a policy.
Note that in the example, we could say that
fixed_storageanddynamic_storageare “models” of theStoragePolicyconcept. Of course, we would need to formally define exactly what theStoragePolicyconcepts requires of its models. In this case, it would simply be to define an indexabledatamember variable.