|
Boost : |
From: Brian Martin (brmartin_at_[hidden])
Date: 2004-04-05 05:52:38
Brian Martin wrote:
>I'll have another think about some of the compile time check issues.
I have and have done the following:
1) Compile time checks would be nice but are basically impossible. At least the ones that count. Such as:
subrange<int, 1, 20> sub_20(30); or sub_20 = 300;
Pascal traps this kind of thing but C++ can't, as far as I can see. Runtime only, I'm afraid.
I am of the opinion that the compile time checks that were given in Maciej's example code are of limited use since the real benefit of subranges is runtime (in my humble opinion). In the example code, it was possible to assign/copy different subrange types, provided the source had a range inside the destination. For now, my subrange doesn't allow different subrange types to mix.
2) Agonised over whether or not to remove the typename T (I call it a "base type" a la Pascal terminology) from the template. In my previous post I said that it allows any type to be stored in the subrange, forgetting of course that you can't have doubles, classes and C strings as non-type template parameters. Doh! Actually, this is what I want since subranges of classes is a bit odd. Floating point subranges would have been nice, but Pascal doesn't allow them either. There is a way of doing it, but it messes up the syntax.
I've kept the base type because you waste storage if you're storing anything smaller than a long. There's no class overhead (on my compiler) so this doesn't make the wastage trivial. The waste is ok if you're only using a few subranges but in one project I'm storing potentially large numbers of subranges (of shorts) in STL containers and then reading/writing them in binary from/to files. Didn't like the files being 2 times bigger than they should be. So, reluctantly, I've kept the base type.
3) I've used a conversion operator. I usually avoid these but in this case it integrates subranges nicely into the type system so that built in types and subranges can mix freely in expressions. The template is, after all, supposed to be a (restricted) integral type.
4) Removed operator~(). It always fails since the value gets its upper bits set to 1 which will exceed the subrange unless you've set the upper limit to the maximum the type can store. There are obvious problems with signed types too.
6) Have attached some code - the subrange class itself and a test program for anyone who wants to give it a go.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk