Browse DevX
Sign up for e-mail newsletters from DevX


Enforcing Compile-time Constraints

Implementing some constraints require too much elbow grease. Wouldn't it be great to find a way to generically implement those more abstract constraints ? The following solution shows you how to do just that.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

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.

Thanks for your registration, follow us on our social networks to keep up-to-date