|
Boost : |
From: Jost, Andrew (Andrew_Jost_at_[hidden])
Date: 2005-07-09 20:50:30
This is my first post to the Boost distribution list, so please feel
free to speak up if you find any part of this message to be outside the
normal decorum.
I am curious if there is support for what I'm calling a "dual_state"
template class. Anyone familiar with Perl will instantly recognize the
parallel. The idea is to attach a "statedness" value to arbitrary
objects, allowing us to consider them defined or undefined. Newly
constructed dual_state objects are undefined. For example,
// -- begin
template < class T >
class dual_state {
...
};
dual_state<int> a;
a.defined(); // FALSE
defined(a); // same thing
// -- end
We can "define" a dual_state object by assigning a value to it, either
as a base type, T, or as another dual_state object:
// -- begin
// assign an int to a
a = 5;
a.defined() // TRUE
// assign another dual_state<int> to a
dual_state<int> b;
b = a;
b.defined(); // TRUE
// -- end
We can undefine a defined dual_state object:
// -- begin
a.undefine();
undefine(b);
// -- end
In addition, we can utilize an instance of another class, the
"undefined_object", to interrogate or set the defined property of a
dual_state object:
// -- begin
const class undefined_object {} undef;
a = undef;
a.defined(); // FALSE
a == undef; // same thing
// -- end
The dual_state class provides a conversion to T. This conversion will,
for an undefined dual_state object, return default T objects generated
using the expression "T()". As an aside, it seems Boost.value_init may
provide a more general solution that is worth considering.
There is no conversion to T& because some compilers are utterly confused
by such conversions. To make dual_state compatible with large or
uncopyable objects, two explicit conversions are provided:
// --begin
template < class T >
class dual_state {
...
const T& value() const;
T& define();
};
// -- end
The value() member is straightforward. As for define(), it is necessary
to first define the dual_state object before assigning it a value. The
operator= member normally takes care of this step, but when dealing with
the T reference directly we must explicitly use define(). An example
using define() is shown below:
// -- begin
dual_state<int> x;
cin >> x.define();
// -- end
In Perl, the defined/undefined concept is tremendously useful, so I
would expect similar utility in C++. I have not given any thought to
what a dual_state<bool> is or how it is related to Boost.tribool.
Thanks to everyone who took the time to read this whole post. I am open
to all suggestions, including a better name -- "dual_state" is quite
incongruent, but I can't think of anything better. Here are some
additional poor suggestions: bistate, managed, switched, stated,
definable.
-- Andrew M. Jost
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk