Just a thought that woke me up this morning. A means of providing 'property' type constructs in C++ classes similar to python properties.
Header
#ifndef _HXX_CPROP
#define _HXX_CPROP
/**
* Helper class to connect a 'property' in a
* c++ class to getter/setter methods
*
*/
template<class T, typename V>
class property {
public:
/**
* \brief ctor
*/
property(T* _target,
V (T::*_getter)(void) const = (V (T::*)(void))0L,
V (T::*_setter)(V value) = (V (T::*)(V value))0L) ;
/**
* assignment operator. Provides setter
* parent.field = value
* functionality
*/
V operator=(V value) ;
/**
* coveration operator, provides 'getter'
*/
operator V() const ;
private:
T *target ;
V (T::*getter)(void) const ;
V (T::*setter)(V value) ;
} ;
/*
*
*/
template<class T, typename V>
property<T,V>::property(T* _target,
V (T::*_getter)(void) const /* = (void *)0L */,
V (T::*_setter)(V value) /* = (void *)0L */)
: target(_target),
getter(_getter),
setter(_setter)
{
}
/*
*
*/
template<class T, typename V>
inline V property<T,V>::operator=(V value)
{
return (target->*setter)(value) ;
}
/*
*
*/
template<class T, typename V>
inline property<T,V>::operator V() const
{
return (target->*getter)() ;
}
#endif /* _HXX_CPROP */
Test Case
#include <iostream>
#include <string>
#include "cprop.hxx"
using namespace std ;
class testClass {
public:
testClass() ;
property<testClass, bool> flag ;
private:
bool _flag ;
bool setFlag(bool f) ;
bool getFlag() const ;
} ;
testClass::testClass()
: flag(this, &testClass::getFlag, &testClass::setFlag),
_flag(false)
{
}
bool testClass::setFlag(bool f)
{
_flag = f ;
if( _flag )
cout << "flag on" << endl ;
else
cout << "flag off" << endl ;
return f ;
}
bool testClass::getFlag() const
{
return _flag ;
}
int main(int argc, char **argv)
{
testClass c ;
c.flag = true ;
c.flag = false ;
c.flag = true ;
cout << "flag state = " << c.flag << endl ;
}