advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
To facilitate the implementation of constraints, new language features are necessary. One such feature is a keyword that indicates a constraint. This keyword will instruct the compiler to evaluate the constraint for every template instance automatically. An implementation can also use this keyword to remove the constraint's code from the executable. Which other features do you think can facilitate the design and implementation of constraints? Let us know in our C++ Discussion Forum.
Partners & Affiliates
advertisement
advertisement
advertisement
Average Rating: 3.7/5 | Rate this item | 3 users have rated this item.
 

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. 


advertisement
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.

  Next Page: Presenting the Problem
Page 1: IntroductionPage 3: Design Improvements
Page 2: Presenting the Problem 
Please rate this item (5=best)
 1  2  3  4  5
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About