
eneric containers and algorithms often impose certain restrictions on the objects that they manipulate. For example, the
std::sort() algorithm requires that the elements on which it operates shall define the < operator. Enforcing this constraint is easy: the compiler tries to invoke this operator for the given type. If such an operator doesn't exist, you get a compilation error:
#include <algorithm>
struct S{}; //doesn't define operator <
int main()
{
S s[2];
std::sort(s, s+2); //error: 'operator<' //
not implemented
//in type 'S'
}
However, not all constraints can be expressed and enforced that easily. More abstract constraints such as "must have a base class" or "must be a POD type" require more code maneuvers and resourcefulness from the programmer. The following sections will demonstrate how to implement such constraints in a generic fashion.

How can you enforce compile-time constraints on objects in a generic fashion?

Use "constraint templates" to automate the enforcement of compile-time constraints.