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_checked_integer(std::istream &is, int
&result_value)
{
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::failbit);
return is;
}
result_value = value;
return is;
}
I want a type to help write read_range_checked_integer more succinctly. For
example:
std::istream &read_range_checked_integer(std::istream &is, int
&result_value)
{
range_checked_integer<0, 64> value;
if (!(is >> value))
{
std::cout << "failed to extract range_checked_integer<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_integer?
Thanks alot. 11 4586
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_checked_integer(std::istream &is, int &result_value) { 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::failbit); return is; }
result_value = value; return is; }
I want a type to help write read_range_checked_integer more succinctly. For example:
std::istream &read_range_checked_integer(std::istream &is, int &result_value) { range_checked_integer<0, 64> value; if (!(is >> value)) { std::cout << "failed to extract range_checked_integer<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_integer? 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.failbit);
else
i.value = tmp;
return s;
}
ostream& operator <<(ostream& s, const RInt& i)
{
s << i.value;
return s;
}
#endif //_RINT_H_
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_error("out of range");
val = v;
}
bounded(bounded const &init) : val(init.v) {}
bounded &operator=(T const &v) {
if (check(v))
throw std::domain_error("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.
"Jerry Coffin" <jc*****@taeus.com> wrote in message
news:11**********************@o13g2000cwo.googlegr oups.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_error("out of range"); val = v; }
bounded(bounded const &init) : val(init.v) {}
bounded &operator=(T const &v) { if (check(v)) throw std::domain_error("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)?
Jason Heyes wrote: "Jerry Coffin" <jc*****@taeus.com> wrote in message news:11**********************@o13g2000cwo.googlegr oups.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_error("out of range"); val = v; }
bounded(bounded const &init) : val(init.v) {}
bounded &operator=(T const &v) { if (check(v)) throw std::domain_error("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
"Karl Heinz Buchegger" <kb******@gascad.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.
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.
"Jerry Coffin" <jc*****@taeus.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.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?
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.
"Jerry Coffin" <jc*****@taeus.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.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?
Jason Heyes wrote:
[ ... ] 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?
Yes, when it's important that the variable stay within certain bounds.
--
Later,
Jerry.
The universe is a figment of its own imagination.
"Jerry Coffin" <jc*****@taeus.com> wrote in message
news:11**********************@l41g2000cwc.googlegr oups.com... Jason Heyes wrote:
[ ... ]
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?
Yes, when it's important that the variable stay within certain bounds.
Often you don't need a bounded type to keep a variable within bounds. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
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...
|
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....
|
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:...
|
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...
|
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...
|
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...
|
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:
|
by: Kemmylinns12 |
last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
|
by: Naresh1 |
last post by:
What is WebLogic Admin Training?
WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
|
by: Arjunsri |
last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
|
by: WisdomUfot |
last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific technical details, Gmail likely implements measures...
|
by: Matthew3360 |
last post by:
Hi,
I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
|
by: Oralloy |
last post by:
Hello Folks,
I am trying to hook up a CPU which I designed using SystemC to I/O pins on an FPGA.
My problem (spelled failure) is with the synthesis of my design into a bitstream, not the C++...
|
by: Carina712 |
last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
|
by: Rahul1995seven |
last post by:
Introduction:
In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
|
by: Ricardo de Mila |
last post by:
Dear people, good afternoon...
I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control.
Than I need to discover what...
| |