|
Boost : |
From: Aleksey Gurtovoy (alexy_at_[hidden])
Date: 2000-02-03 05:28:23
I have in mind a small (pretty??) class, which seems to me to be a yet
another candidate to our boost utility library. I've seen it to be
reinvented at least 2 times after I'd invented it myself , so I will be not
much surprised if someone say 'I have this one too'..
And even if you didn't, but you had ever written a code which assign some
temporary value to a variable at some place in a block (usually at the
beginning), and restore the old value at the end of it, I am sure you would
appreciate this class :). It does exactly such thing - assign a new value to
a variable, storing the old one within itself, and restore the original
value in its destructor.
So the class itself:
namespace boost {
template<class T>
class temp_value
{
public:
typedef T value_type;
temp_value( T* object_ptr, const T& new_value )
: object_ptr_( object_ptr )
, old_value_( *object_ptr ) { *object_ptr_ = new_value; }
~temp_value() { *object_ptr_ = old_value_; }
private:
T old_value_;
T* object_ptr_;
};
}
(Dave, I know, it must be renamed to 'temporary_value' =), and I agree with
you, unless we choose a totally different name.)
And a typical usage (and test) may look like this:
void temp_value_test() {
bool flag = true;
int count = 15;
if ( flag ) {
boost::temp_value<bool> tmp( &flag, false );
assert( !flag );
if ( !flag ) {
boost::temp_value<int> tmp( &count, 0 );
assert( !count );
}
assert( count == 15 );
}
assert( flag );
}
Any thoughts about it?
-Alexy
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk