B
Brent Ritchie
Hello,
This is my first attempt at template programming so please bear with me.
This is what I have so far:
Property.h --------------------------
#ifndef PROPERTY_H_
#define PROPERTY_H_
enum Access{ READ, WRITE, FULL };
template<typename T, Access type = FULL>
class Property
{
public:
Property(const T& val, T (*getter)(T) = defaultGet, T (*setter)(T,
T) = defaultSet ): value(val) { Get = getter; Set = setter; }
virtual operator T() { return Get(value); }
virtual T operator=( T& val ) { return Set(value, val); }
protected:
T value;
T (*Get) (T);
T (*Set) (T, T);
static T defaultGet(T val) { return val; }
static T defaultSet(T dest, T source) { dest = source; }
};
#endif
and here is my test program:
main.cpp ---------------------------------
#include <cstdlib>
#include <iostream>
#include "Property.h"
static int anotherGetter(int value) { return 10; }
int main(int argc, char *argv[])
{
Property<int> t(1);
std::cout << t << std::endl;
t = 5;
std::cout << t << std::endl;
t = 2;
std::cout << t << std::endl;
// Up to here everything works fine but:
Property<int> f(1, anotherGetter);
std::cout << f << std::endl; // This returns 10 like it's supposed to
f = 5;
std::cout << f << std::endl;
// But this returns 5 not 10
f = 2;
std::cout << f << std::endl;
// And again this returns 2 not 10.
system("pause");
}
My question is why does it work the way I intended the first time but not
the second or third time?
Any help would be appreciated
This is my first attempt at template programming so please bear with me.
This is what I have so far:
Property.h --------------------------
#ifndef PROPERTY_H_
#define PROPERTY_H_
enum Access{ READ, WRITE, FULL };
template<typename T, Access type = FULL>
class Property
{
public:
Property(const T& val, T (*getter)(T) = defaultGet, T (*setter)(T,
T) = defaultSet ): value(val) { Get = getter; Set = setter; }
virtual operator T() { return Get(value); }
virtual T operator=( T& val ) { return Set(value, val); }
protected:
T value;
T (*Get) (T);
T (*Set) (T, T);
static T defaultGet(T val) { return val; }
static T defaultSet(T dest, T source) { dest = source; }
};
#endif
and here is my test program:
main.cpp ---------------------------------
#include <cstdlib>
#include <iostream>
#include "Property.h"
static int anotherGetter(int value) { return 10; }
int main(int argc, char *argv[])
{
Property<int> t(1);
std::cout << t << std::endl;
t = 5;
std::cout << t << std::endl;
t = 2;
std::cout << t << std::endl;
// Up to here everything works fine but:
Property<int> f(1, anotherGetter);
std::cout << f << std::endl; // This returns 10 like it's supposed to
f = 5;
std::cout << f << std::endl;
// But this returns 5 not 10
f = 2;
std::cout << f << std::endl;
// And again this returns 2 not 10.
system("pause");
}
My question is why does it work the way I intended the first time but not
the second or third time?
Any help would be appreciated