Re: Unsignedness of std::size_t
Kaba <REkalleMOunderscoreVErutanenME@hotmail.com> wrote in
news:MPG.208c8846e512515f989899@news.cc.tut.fi:
I think it is essential that 1 bit of the integer be sacrificed for the
sake of code that can detect such frequent mistakes.
This seems to be contrary to the general philosophy of C/C++. Otherwise,
the language would deal with this directly in how it converts signed
values to unsigned values. The language seems to chose performance and
leaves correctness to the writer.
If you really want your interface to make these types of errors more
difficult, you can create a class that wraps your desired behavior and
use that instead of the int and unsigned types that are so problematic
because of the language rules.
template<unsigned Low,unsigned Hi> struct SizeT_Range{
size_t myValue;
SizeT_Range(size_t x):myValue(x){
if(x<Low ||x>Hi)
throw std::out_of_range("invalid Range used");
}
operator size_t(){return myValue;}
};
class Test{
typedef SizeT_Range<1,100> TestRange;
public:
Test(TestRange x ):y(x){
}
size_t y;
};
called as
int i=-1;
Test(i);
You could even #ifdef this to use size_t in release if performance was a
worry.
Or you could leave the Library alone and just use SizeT_Range in your
calls where you think you need validation.
Test(SizeT_Range<1,100>(i));
OB
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]