1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #include <iostream>
#include <fstream>
#include <cassert>
template< class T >
struct SetterUtil
{
typedef bool (*check_function)(T toCheck);
typedef bool (*ref_check_function)(T const & toCheck);
};
template< class T, class Verif=typename SetterUtil<T>::ref_check_function >
class Setter
{
public:
typedef T value_type;
typedef Verif check_type;
explicit Setter(value_type *pValue, check_type checker=0)
: m_pValue(pValue), m_checker(checker)
{ }
bool Set(value_type const & val) const
{
bool ok = true;
if(m_checker != 0)
ok = m_checker(val);
if(ok)
*m_pValue = val;
return ok;
}
private:
int * m_pValue;
check_type m_checker;
};
template< class T, class Verif >
std::istream & operator>> (std::istream & is, Setter< T, Verif > const &setter)
{
T val;
is >> val;
setter.Set(val);
return is;
}
class Foo
{
private:
int valeur;
static bool checkValeur(int newVal)
{
assert(newVal != 100); //par exemple ou une levée d'exception
if(newVal != 100)
return true;
return false;
}
public:
typedef Setter<int, SetterUtil<int>::check_function> setter_type;
setter_type getSetValeur()
{
return setter_type(&valeur, checkValeur);
}
};
void TestProxy(void)
{
Foo f;
std::ifstream file ("data.txt");
file >> f.getSetValeur();
file.close();
} |