Sponsored Link •
|
Summary
The December 2004 issue of the C/C++ Users Journal has just come out and contains an article I wrote "Constrained Value Types using Policies" which discusses how to use policies to define special cases of value type which must conform to specific ranges or sets of values.
Advertisement
|
A recent article I wrote on constrained value types using policies is now available in the December 2004, issue of C/C++ Users Journal.
A constrained value type is a value type such as an integer or float which must fit a set of constraints. For example a bounded range, values divisible by some factor, etc. A very straightforward example is a double which must be non-negative. Defining such a type can be done as follows:
struct non_negative_double_constraint { typedef double value; static void assign(const value& rvalue, value& lvalue) { if (rvalue < 0.0) { throw 0; } lvalue = rvalue; } }; typedef cv::constrained_value < non_negative_double_constraint > non_negative_double; int main() { non_negative_double d = 1.0; // fine d = -1.0; // throws an exception; }
The non_negative_double_constraint represents the policy. A policy type typically has only static members which are used to define the behaviour of another type. A policy is usually passed as a template argument. Using policies allows the constrained_value type to be as generic as possible. For example the constraint policy may always assign the nearest legal value (a saturation policy), or apply a modulo (e.g. degrees of the circle) or whatever, just use your imagination.
More example of constrained types and the constrained_value source code itself is freely available on my web site cdiggins.com.
Special acknowledgement to Jeff Garland whose work of the same name inspired the article and the type, as well as other members of the Boost community who made several useful and insightful suggestions.
Have an opinion? Readers have already posted 2 comments about this weblog entry. Why not add yours?
If you'd like to be notified whenever Christopher Diggins adds a new entry to his weblog, subscribe to his RSS feed.
Christopher Diggins is a software developer and freelance writer. Christopher loves programming, but is eternally frustrated by the shortcomings of modern programming languages. As would any reasonable person in his shoes, he decided to quit his day job to write his own ( www.heron-language.com ). Christopher is the co-author of the C++ Cookbook from O'Reilly. Christopher can be reached through his home page at www.cdiggins.com. |
Sponsored Links
|