I've written a simple container template class to contain a single
value. This emits a signal when the value is changed (it's used as a
notifier of changes), and listeners can connect to its changed signal.
i.e. field<int> i(2);
i = 4; // field<int>::m_value = 4; changed signal is emitted.
Currently, the contained value may be accessed via get_value() and
set_value() methods, and for ease of use, operator= and some type
conversions are provided. However, accessing a member function
requires a call to get_value(), and I'd like to overload operator->
and operator* to allow access. Ideally, I'd like a const version
(changes to the value are not allowed) and a non-const version, which
allows changes and emits a signal. However, I can't see that this is
possible (condensed for brevity):
template<typename T>
class field {
private:
value_type m_value;
SigC::Signal0<void> m_signal_changed; // libsigc++ signal type.
public:
typedef T value_type;
field(): m_value() {}
field(const value_type& value): m_value(value) {}
field(const field<value_type>& rhs): m_value(rhs.m_value),
m_signal_changed() {}
virtual ~field() {}
value_type& get_value() { return m_value; }
const value_type& get_value() const { return m_value; }
void set_value(const value_type& value)
{ m_value = value; m_signal_changed.emit(); }
field<value_type>& operator = (const field<value_type>& rhs)
{ set_value(rhs.m_value); return *this; }
field<value_type>& operator = (const value_type& rhs)
{ set_value(rhs); return *this; }
operator const value_type& () const { return m_value; }
SigC::Signal0<void>& signal_changed() { return m_signal_changed; }
}; // class field
If I provide a method like this:
const value_type *operator -> () { return &m_value; }
this is OK, but for the non-const version, I want to do this:
value_type *operator -> () { return &m_value; m_signal_changed() }
i.e. I want to emit the changed signal /after/ the caller has got the
pointer, used the method/member chosen and finished. If I emit the
signal before, the change won't yet have happened. However, I need to
return the pointer, so this is obviously impossible.
In addition, I'd like to make the const version the default (if a
const method is called from a non-const pointer), if possible, so that
the changed signal is only emitted on a genuine state change.
Are either of these possible using standard C++? If not, could anyone
suggest a different design to achieve the goal (signal emission after
value change)?
Many thanks,
Roger
--
Roger Leigh
Printing on GNU/Linux? http://gimp-print.sourceforge.net/
GPG Public Key: 0x25BFB848. Please sign and encrypt your mail.
-----= Posted via Newsfeeds.Com, Uncensored Usenet News =-----
http://www.newsfeeds.com - The #1 Newsgroup Service in the World!
-----== Over 100,000 Newsgroups - 19 Different Servers! =-----