Я пишу свойства в C ++.Я придумал этот код (не так хорошо, как показано ниже).
Тогда я хотел сделать это возможным, чтобы я мог написать Property<int>&
и использовать любую версию.Я придумал ниже.У меня две проблемы.
1) В данный момент у меня возникает ошибка компиляции при вызове fn (a);
error C2243: 'type cast' : conversion from 'Property1<T> *' to 'Property<T> &' exists, but is inaccessible
2) Можно ли написать это таким образом, чтобы мне не нужно было указывать его Property1 или Property2?
Код, который я набрал
#include <cstdio>
#include <functional>
template <class T>
class Property{
Property(const Property&p) {}
Property() {}
public:
virtual Property& operator=(const Property& src)=0;
virtual Property& operator=(const T& src)=0;
virtual operator T() const=0;
};
template <class T>
class Property1 : Property<T> {
T v;
public:
Property1(const Property1&p) {*this=static_cast<T>(p);}
//Property1() { printf("ctor %X\n", this);}
Property1(){}
Property& operator=(const Property& src) { return*this=static_cast<T>(src); }
Property& operator=(const T& src) {
printf("write %X\n", this);
v = src;
return *this;
}
operator T() const {
printf("Read %X\n", this);
return v;
}
};
template <class T>
class Property2 : Property<T> {
typedef T(*Gfn)();
typedef void(*Sfn)(T);
Gfn gfn;
Sfn sfn;
public:
Property2(const Property2&p) {*this=static_cast<T>(p);}
//Property2() { printf("ctor %X\n", this);}
Property2(Gfn gfn_, Sfn sfn_):gfn(gfn_), sfn(sfn_) {}
Property& operator=(const Property& src) { return*this=static_cast<T>(src); }
Property& operator=(const T& src) {
printf("write %X\n", this);
sfn(src);
return *this;
}
operator T() const {
printf("Read %X\n", this);
return gfn();
}
};
void set(int v) {}
int get() {return 9;}
Property1<int> a, b;
Property2<int> c(get,set), d(get,set);
void fn(Property<int>& v) { v=v=31; }
int main(){
a=b=5;
c=d=11;
a=c=b=d=15;
fn(a);
fn(c);
}