473,543 Members | 2,550 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

An integer type with range checking.

I would like to be able to extract an integer from a stream without having
to write a test when I want the integer within some range. Unfortunately
there is no range-checked integer type in the standard C++ library. Consider
the following function:

std::istream &read_range_che cked_integer(st d::istream &is, int
&result_valu e)
{
int value;
if (!(is >> value))
{
std::cout << "failed to extract integer" << std::endl;
return is;
}

if (!(value >= 0 && value < 64))
{
std::cout << "extracted integer is out of range" << std::endl;
is.setstate(std ::ios_base::fai lbit);
return is;
}

result_value = value;
return is;
}

I want a type to help write read_range_chec ked_integer more succinctly. For
example:

std::istream &read_range_che cked_integer(st d::istream &is, int
&result_valu e)
{
range_checked_i nteger<0, 64> value;
if (!(is >> value))
{
std::cout << "failed to extract range_checked_i nteger<0, 64>" <<
std::endl;
return is;
}

result_value = value.get_int() ;
return is;
}

Can somebody help me find a type that behaves like range_checked_i nteger?
Thanks alot.
Jul 23 '05 #1
11 4665
Jason Heyes wrote:
I would like to be able to extract an integer from a stream without having
to write a test when I want the integer within some range. Unfortunately
there is no range-checked integer type in the standard C++ library. Consider
the following function:

std::istream &read_range_che cked_integer(st d::istream &is, int
&result_valu e)
{
int value;
if (!(is >> value))
{
std::cout << "failed to extract integer" << std::endl;
return is;
}

if (!(value >= 0 && value < 64))
{
std::cout << "extracted integer is out of range" << std::endl;
is.setstate(std ::ios_base::fai lbit);
return is;
}

result_value = value;
return is;
}

I want a type to help write read_range_chec ked_integer more succinctly. For
example:

std::istream &read_range_che cked_integer(st d::istream &is, int
&result_valu e)
{
range_checked_i nteger<0, 64> value;
if (!(is >> value))
{
std::cout << "failed to extract range_checked_i nteger<0, 64>" <<
std::endl;
return is;
}

result_value = value.get_int() ;
return is;
}

Can somebody help me find a type that behaves like range_checked_i nteger?
Thanks alot.


Create a class for ranged integer values and overload the stream
operators. For example:
// rint.h

#ifndef _RINT_H_
#define _RINT_H_

#include <iostream>

class RInt
{
public:
RInt(int min, int max);
virtual ~RInt();

friend std::istream& operator >>(std::istream & s, RInt& i);
friend std::ostream& operator <<(std::ostream & s, const RInt& i);
private:
int value, min, max;
};
// rint.cpp

#include "rint.h"
#include <iostream>

using namespace std;

RInt::RInt(int min, int max) : value (min), min (min), max (max)
{
}

RInt::~RInt()
{
}

istream& operator >>(istream& s, RInt& i)
{
int tmp;
s >> tmp;

if (tmp < i.min || tmp > i.max)
s.clear(s.failb it);
else
i.value = tmp;

return s;
}

ostream& operator <<(ostream& s, const RInt& i)
{
s << i.value;
return s;
}

#endif //_RINT_H_
Jul 23 '05 #2
Jason Heyes wrote:
I would like to be able to extract an integer from a stream without
having to write a test when I want the integer within some range.


This may be a bit more elaborate than you were thinking of, but it
should do the job:

// Partially tested code. Compiles and works to at least some degree,
// but may still harbor bugs.
#include <exception>
#include <iostream>
#include <functional>

template <class T, T lower, T upper, class less=std::less< T> >
class bounded {
T val;

static bool check(T const &value) {
return less()(value, lower) || less()(upper, value);
}

public:
bounded() : val(lower) { }

bounded(T const &v) {
if (check(v))
throw std::domain_err or("out of range");
val = v;
}

bounded(bounded const &init) : val(init.v) {}

bounded &operator=(T const &v) {
if (check(v))
throw std::domain_err or("Out of Range");
val = v;
return *this;
}

operator T() const { return val; }

friend std::istream &operator>>(std ::istream &is, bounded &b) {
T temp;
is >> temp;

if (check(temp))
is.setstate(std ::ios::failbit) ;
b.val = temp;
return is;
}
};

The most obvious difference is that this passes the underlying type as
a template parameter instead of making it part of the name. This makes
ranges of various different types about equally easy to work with --
e.g. you can just about as easily do a bounded<double, 0.001, 0.1> as a
bounded<int, 0, 512> like you asked for.

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 23 '05 #3
"Jerry Coffin" <jc*****@taeus. com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
This may be a bit more elaborate than you were thinking of, but it
should do the job:

// Partially tested code. Compiles and works to at least some degree,
// but may still harbor bugs.
#include <exception>
#include <iostream>
#include <functional>

template <class T, T lower, T upper, class less=std::less< T> >
class bounded {
T val;

static bool check(T const &value) {
return less()(value, lower) || less()(upper, value);
}

public:
bounded() : val(lower) { }

bounded(T const &v) {
if (check(v))
throw std::domain_err or("out of range");
val = v;
}

bounded(bounded const &init) : val(init.v) {}

bounded &operator=(T const &v) {
if (check(v))
throw std::domain_err or("Out of Range");
val = v;
return *this;
}

operator T() const { return val; }

friend std::istream &operator>>(std ::istream &is, bounded &b) {
T temp;
is >> temp;

if (check(temp))
is.setstate(std ::ios::failbit) ;
b.val = temp;
return is;
}
};

The most obvious difference is that this passes the underlying type as
a template parameter instead of making it part of the name. This makes
ranges of various different types about equally easy to work with --
e.g. you can just about as easily do a bounded<double, 0.001, 0.1> as a
bounded<int, 0, 512> like you asked for.


Looks good. You allow for implicit conversion between the bounded type and
type T. Why, then, do you need operator=(T const &v)?

Jul 23 '05 #4
Jason Heyes wrote:

"Jerry Coffin" <jc*****@taeus. com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
This may be a bit more elaborate than you were thinking of, but it
should do the job:

// Partially tested code. Compiles and works to at least some degree,
// but may still harbor bugs.
#include <exception>
#include <iostream>
#include <functional>

template <class T, T lower, T upper, class less=std::less< T> >
class bounded {
T val;

static bool check(T const &value) {
return less()(value, lower) || less()(upper, value);
}

public:
bounded() : val(lower) { }

bounded(T const &v) {
if (check(v))
throw std::domain_err or("out of range");
val = v;
}

bounded(bounded const &init) : val(init.v) {}

bounded &operator=(T const &v) {
if (check(v))
throw std::domain_err or("Out of Range");
val = v;
return *this;
}

operator T() const { return val; }

friend std::istream &operator>>(std ::istream &is, bounded &b) {
T temp;
is >> temp;

if (check(temp))
is.setstate(std ::ios::failbit) ;
b.val = temp;
return is;
}
};

The most obvious difference is that this passes the underlying type as
a template parameter instead of making it part of the name. This makes
ranges of various different types about equally easy to work with --
e.g. you can just about as easily do a bounded<double, 0.001, 0.1> as a
bounded<int, 0, 512> like you asked for.


Looks good. You allow for implicit conversion between the bounded type and
type T. Why, then, do you need operator=(T const &v)?


Think of:
bounded< int, 1, 5 > a = 3;
bounded< int, 5, 10 > b = 8;
a = b;

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 23 '05 #5
"Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message
news:42******** *******@gascad. at...
Jason Heyes wrote:

Looks good. You allow for implicit conversion between the bounded type
and
type T. Why, then, do you need operator=(T const &v)?


Think of:
bounded< int, 1, 5 > a = 3;
bounded< int, 5, 10 > b = 8;
a = b;


Oh I see.
Jul 23 '05 #6
Jason Heyes wrote:

[ ... ]
Looks good. You allow for implicit conversion between the bounded
type and type T. Why, then, do you need operator=(T const &v)?


Instantiating a template over two different sets of parameters results
in two completely unrelated types. The copy constructor is ONLY used to
assign between two objects of exactly the same type.

As such, without this, assignment from one bounded type to a different
bounded type would involve two type conversions -- but only one can be
done implicitly, so all such assignments would require explicit type
casts (which I'd consider undesirable).

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 23 '05 #7
"Jerry Coffin" <jc*****@taeus. com> wrote in message
news:11******** **************@ z14g2000cwz.goo glegroups.com.. .

Instantiating a template over two different sets of parameters results
in two completely unrelated types. The copy constructor is ONLY used to
assign between two objects of exactly the same type.

As such, without this, assignment from one bounded type to a different
bounded type would involve two type conversions -- but only one can be
done implicitly, so all such assignments would require explicit type
casts (which I'd consider undesirable).


Would you consider defining operator+ and operator- for bounded?
Jul 23 '05 #8
Jason Heyes wrote:

[ ... ]
Would you consider defining operator+ and operator- for bounded?


I've considered going whole-hog and adding the full range of operators
to it, but so far I've never seen a benefit that justified the work.
OTOH, if somebody else sees it as a worthwhile way to spend their time,
they're certainly more than welcome to take the code and run with it.

In case that wasn't clear: the code is in the public domain, so anybody
can treat it as if they had written it themself, and use it in any way
they please, modify it as they see fit, etc. If I was going to control
it at all, the sole stipulation would be that it never be published as
"free software". I won't try to enforce that, but if you do it, don't
plan on ever being invited to any of my parties. Better yet, make sure
I never know about it. :-)

--
Later,
Jerry.

The universe is a figment of its own imagination.

Jul 23 '05 #9
"Jerry Coffin" <jc*****@taeus. com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .

I've considered going whole-hog and adding the full range of operators
to it, but so far I've never seen a benefit that justified the work.


As long as I can easily read a bounded type from a stream, I'm happy. :-)
Beyond that I don't see the need for a bounded type. For example, I wouldn't
try to replace ordinary ints with bounded ones. Would you?

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
648
by: REH | last post by:
If the is_modulo field of the numeric_limits class is true for signed integer types, can I assume that overflow for such types is defined behavior? If so, is the behavior the same regardless of implementation? Also, if the range of an integer type is not symmetrical around zero (i.e., 2's comp.), is it safe to assume that the extra...
4
3360
by: rz0 | last post by:
Hi all, This is a question about both C89 and C99 and is based on my partial reading of the standard drafts (one from before C89 but mainly N1124). If appropriate, please give a separate answer for each version of the language. Let's consider the conversion from a given floating real type to a specific integer type.
17
3449
by: Yogi_Bear_79 | last post by:
I have the following code: sscanf(line, "%d", n_ptr) !=1 || n_ptr <=0; It only partially works. If the user types a character other than 0-9 to start the string it fails. However as long as the first character is an integer it will allow letters in the following places for Example:
21
4081
by: Frederick Gotham | last post by:
I set about trying to find a portable way to set the value of UCHAR_MAX. At first, I thought the following would work: #define UCHAR_MAX ~( (unsigned char)0 ) However, it didn't work for me. Could someone please explain to me what's going on? I would have thought that the following happens: (1) The literal, 0, whose type is int, gets...
40
2765
by: Robert Seacord | last post by:
The CERT/CC has released a beta version of a secure integer library for the C Programming Language. The library is available for download from the CERT/CC Secure Coding Initiative web page at: http://www.cert.org/secure-coding/ The purpose of this library is to provide a collection of utility functions that can assist software developers...
232
13071
by: robert maas, see http://tinyurl.com/uh3t | last post by:
I'm working on examples of programming in several languages, all (except PHP) running under CGI so that I can show both the source files and the actually running of the examples online. The first set of examples, after decoding the HTML FORM contents, merely verifies the text within a field to make sure it is a valid representation of an...
4
9938
by: Raymond | last post by:
Source: http://moryton.blogspot.com/2007/08/detecting-overflowunderflow-when.html Example from source: char unsigned augend (255); char unsigned const addend (255); char unsigned const sum (augend + addend); if (sum < augend)
130
6637
by: euler70 | last post by:
char and unsigned char have specific purposes: char is useful for representing characters of the basic execution character set and unsigned char is useful for representing the values of individual bytes. The remainder of the standard integer types are general purpose. Their only requirement is to satisfy a minimum range of values, and also...
30
4247
by: =?ISO-8859-1?Q?Tom=E1s_=D3_h=C9ilidhe?= | last post by:
Let's say we had a simple function for returning the amount of days in a month: unsigned DaysInMonth(unsigned const month) { switch (month) { case 8: case 3: case 5:
0
7399
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7341
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7584
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7729
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7332
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
1
5258
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4884
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3385
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3386
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.