I'm trying to provide a uniform interface for two similar types, one dealing with doubles and the other with floats.
class float_type {
float_type() { /* does floaty stuff */ }
float f();
};
class double_type {
double_type() { /* does doubly stuff */ }
double f();
};
I want to write a class that allocates one or the other depending on what the program needs to do.
I'm perfectly fine with the result of float_type::f() being converted to double. In fact, it happens anyway.
I tried to write it like this:
class union_type {
bool is_double;
char mem[ sizeof(double_type) > sizeof(float_type)
? sizeof(double_type) : sizeof(float_type) ];
public:
float_or_double_value_reader(bool is_double)
: is_double(is_double)
{
if (is_double) new(mem) double_type();
else new(mem) float_type();
}
~float_or_double_value_reader() {
if (is_double) delete static_cast<double_type*>(mem);
else delete static_cast< float_type*>(mem);
}
double f() {
return (is_doubled
? static_cast<double_type*>(mem)->f()
: static_cast< float_type*>(mem)->f()
);
}
};
But I get invalid static_cast from type 'char [128]' to type 'double_type'.
I know I could add a member pointers to point to what new returns,
but that would be redundant, since I already know where mem is located,
so I want to avoid that.
If I use reinterpret_cast instead, I get free(): invalid pointer: at runtime when the union_type is destroyed.
What's the appropriate method of casting here?
reinterpret_cast should be the appropriate method of casting.
However, you can't simply delete reinterpret_cast<double_type*>(mem) because that will not only destroy the object, but also free the memory as if it was allocated with new - which it wasn't.
You can use reinterpret_cast<double_type*>(mem)->~double_type(); to destroy the object without attempting to free the memory.
Of course the above applies to float_type as well.
A better option would be to provide casting operator.
I would have provided a implicit double casting operator to the float class to achieve the same interface
You could use a template base class:
#include <iostream>
template < typename T >
class base_decimal
{
public:
base_decimal(T data) : _data(data) {}
virtual ~base_decimal() {}
T f() { return this->_data; }
base_decimal& operator=(T val) { this->_data = val; }
operator T() { return this->_data; }
friend std::ostream& operator<<(std::ostream& os, const base_decimal& bd)
{
os << bd._data;
return os;
}
private:
T _data;
};
class float_type : public base_decimal<float>
{
public:
float_type(float f) : base_decimal<float>(f)
{
// do float stuff
}
};
class double_type : public base_decimal<double>
{
public:
double_type(double d) : base_decimal<double>(d)
{
// do double stuff
}
};
int main(int argc, char* argv[])
{
float_type f = 1.2f;
double_type d = 2.2;
std::cout << "f = " << f << std::endl;
std::cout << "d = " << d << std::endl;
double rd = d;
double rf = f;
std::cout << "rf = " << rf << std::endl;
std::cout << "rd = " << rd << std::endl;
return 0;
}
Related
This question already has answers here:
What is The Rule of Three?
(8 answers)
Closed 5 years ago.
I was trying my own implementation of a generic container of arbitrary type (similar to boost:any) just to learn about the idiom, and I am trying to understand why my code gives a segmentation fault.
class IValue
{
public:
IValue() = default;
virtual ~IValue() = default;
};
template<typename T>
class Value : public IValue
{
public:
Value(T value) : val(value){}
virtual ~Value() override
{
}
T get()
{
return val;
}
private:
T val;
};
class any
{
public:
template<typename U>
any(U element)
{
elem = new Value<U>(element);
}
~any()
{
delete elem;
}
IValue* get_type_erased_value()
{
return elem;
}
private:
IValue* elem;
};
template<typename T>
T any_cast(any a)
{
Value<T>* stored_element = dynamic_cast<Value<T>*>(a.get_type_erased_value());
if(stored_element)
{
return stored_element->get();
}
else
{
cout << "Any cast failed. Could not cast down to required type\n";
return T();
}
}
struct foo
{
int a;
float b;
char c;
};
ostream& operator<<(ostream& stream, foo& a)
{
stream << '{' << a.a << ',' << a.b << ',' << a.c << '}' << '\n';
return stream;
}
int main()
{
any a = string("Any string value");
any b = int(17);
any c = foo({27,3.5,'g'});
string s = any_cast<string>(a);
int i = any_cast<int>(b);
foo f = any_cast<foo>(c);
cout << "Any string contained: " << s << '\n';
cout << "Any int contained: " << i << '\n';
cout << "Any struct foo contained: " << f << '\n';
return 0;
}
The output is what I desire and the casts seem to work correctly, but the program always crashes at the end. There must be something wrong with the destructor not being called correctly or the deallocation of the pointer. Can someone give me a hint?
Thanks
The implicitly defined copy constructor of your any type just copies the IValue pointer, so both the original object and the copy will delete the same pointer. You need to write a copy constructor that actually copies the stored object.
Whilst trying to debug some code, I created a class to dump the values of a complicated hierarchy of objects to a text file so that I can compare a case where it works against a case where it doesn't. I implemented the class like this (reduced to a bare example):
#include <iostream>
class someOtherClass
{
public:
someOtherClass()
: a(0)
, b(1.0f)
, c(2.0)
{}
int a;
float b;
double c;
};
class logger
{
public:
// Specific case for handling a complex object
logger& operator << ( const someOtherClass& rObject )
{
std::cout << rObject.a << std::endl;
std::cout << rObject.b << std::endl;
std::cout << rObject.c << std::endl;
return *this;
}
// [other class specific implementations]
// Template for handling pointers which might be null
template< typename _T >
logger& operator << ( const _T* pBar )
{
if ( pBar )
{
std::cout << "Pointer handled:" << std::endl;
return *this << *pBar;
}
else
std::cout << "null" << std::endl;
return *this;
}
// Template for handling simple types.
template< typename _T >
logger& operator << ( const _T& rBar )
{
std::cout << "Reference: " << rBar << std::endl;
return *this;
}
};
int main(int argc, char* argv[])
{
logger l;
someOtherClass soc;
someOtherClass* pSoc = &soc;
l << soc;
l << pSoc;
pSoc = nullptr;
l << pSoc;
return 0;
}
I was expecting to get the following output:
0
1
2
Pointer handled:
0
1
2
null
But what I actually get is:
0
1
2
Reference: 010AF7E4
Reference: 00000000
The automatic type deduction appears to be picking the reference implementation and setting the type to someOtherClass* rather than picking the pointer implementation. I'm using Visual Studio 2012.
In logger& operator << ( const _T& rBar ) type T can be a pointer type, so in order to work properly this template needs some restriction:
template< typename _T , typename = typename ::std::enable_if_t<!std::is_pointer<_T>::value> >
logger& operator << ( const _T& rBar )
{
std::cout << "Reference: " << rBar << std::endl;
return *this;
}
Online compiler
This is required because when templates are instantiated the const _T & pBar with _T = someOtherClass * variant will be proffered as conversion sequence required in this case will only include a reference binding which is considered an identity conversion while const _T* pBar variant with _T = someOtherClass will involve a copy-initialization.
Here are a few modifications and annotations which may help as this logging class grows and becomes more mature.
I have attempted to:
a) solve the initial problem of incorrect type deduction.
b) decouple the logger from the things being logged (otherwise your logger has to know about the entire application and all libraries).
c) provide a mechanism for easily allowing logging of any type, even if provided by a third-party library.
#include <iostream>
// I've put the logger and its helpers into a namespace. This will keep code tidy and help with
// ADL.
namespace logging
{
// define a general function which writes a value to a stream in "log format".
// you can specialise this for specific types in std:: if you wish here
template<class T>
void to_log(std::ostream& os, T const& value)
{
os << value;
}
// define a general function objects for writing a log-representation of tyoe T.
// There are 2 ways to customise this.
// a) provide a free function called to_log in the same namespace as your classes (preferred)
// b) specialise this class.
template<class T>
struct log_operation
{
void operator()(std::ostream& os, T const& value) const
{
to_log(os, value);
}
};
// specialise for any pointer
template<class T>
struct log_operation<T*>
{
void operator()(std::ostream& os, T* ptr) const
{
if (!ptr)
os << "null";
else
{
os << "->";
auto op = log_operation<std::decay_t<T>>();
op(os, *ptr);
}
}
};
// the logger is now written in terms of log_operation()
// it knows nothing of your application's types
class logger
{
public:
// Template for handling any type.
// not that this will also catch pointers.
// we will disambiguate in the log_operation
template< typename T >
logger& operator << ( const T& rBar )
{
auto op = log_operation<std::decay_t<T>>();
op(std::cout, rBar);
std::cout << std::endl;
return *this;
}
};
}
class someOtherClass
{
public:
someOtherClass()
: a(0)
, b(1.0f)
, c(2.0)
{}
int a;
float b;
double c;
};
// someOtherClass's maintainer provides a to_log function
void to_log(std::ostream& os, someOtherClass const& c)
{
os << "someOtherClass { " << c.a << ", " << c.b << ", " << c.c << " }";
}
namespace third_party
{
// the is in a 3rd party library. There is no to_log function and we can't write one which will be found with
// ADL...
struct classWhichKnowsNothingOfLogs {};
}
/// ..so we'll specialise in the logging namespace
namespace logging
{
template<>
struct log_operation<::third_party::classWhichKnowsNothingOfLogs>
{
void operator()(std::ostream& os, ::third_party::classWhichKnowsNothingOfLogs const& value) const
{
os << "classWhichKnowsNothingOfLogs {}";
}
};
}
int main(int argc, char* argv[])
{
logging::logger l;
someOtherClass soc;
someOtherClass* pSoc = &soc;
l << soc;
l << pSoc;
pSoc = nullptr;
l << pSoc;
l << third_party::classWhichKnowsNothingOfLogs();
return 0;
}
expected output:
someOtherClass { 0, 1, 2 }
->someOtherClass { 0, 1, 2 }
null
classWhichKnowsNothingOfLogs {}
One class returns 'int', other returns 'double'. What is the signature of method 'GiveMeTheValue' in the interface of both classes.
I want to compile following code:
class Interface
{
public:
virtual arbitrary_type GimeMeTheValue(void) {};
};
class TakeInt : public Interface
{
public:
arbitrary_type GimeMeTheValue(void) {
return 10;
}
};
class TakeDouble : public Interface
{
public:
arbitrary_type GimeMeTheValue(void) {
return 3.14;
}
};
int main()
{
Interface * obj;
obj = new TakeInt();
cout << obj -> GimeMeTheValue() << endl; // It's 10, thank you
obj = new TakeDouble();
cout << obj -> GimeMeTheValue() << endl; // Oh it's 3.14, I love you c++
}
Of course there is no such an "arbitary_type".
This works ...
class Interface
{
public:
virtual void * GimeMeTheValue(void) {};
};
class TakeInt : public Interface
{
public:
void * GimeMeTheValue(void) {
int value = 10;
int * ptr = &value;
return ptr;
}
};
class TakeDouble : public Interface
{
public:
void * GimeMeTheValue(void) {
double value = 3.14;
double * ptr = &value;
return ptr;
}
};
int main()
{
Interface * obj;
obj = new TakeInt();
cout << *( (int *) (obj -> GimeMeTheValue()) ) << endl;
obj = new TakeDouble();
cout << *( (double *) (obj -> GimeMeTheValue()) ) << endl;
}
It is rather complicated to deal with "void *". Are there any other ideas to implement something simple (like in the first code example)? Thank you.
There is no way the base class Interface could know what distinct data type each descendant wants to return. Using different return types defeats the purpose of polymorphism. So the only way I can think to do this is to have GiveMeTheValue() return an object type that knows what kind of value it holds, and then make that object streamable.
enum VariantType {varNull, varInt, varDouble};
struct Variant
{
VariantType Type;
union {
int intValue;
double dblValue;
};
Variant() : Type(varNull) {}
Variant(int value) : Type(varInt), intValue(value) {}
Variant(double value) : Type(varDouble), dblValue(value) {}
void writeTo(std::ostream &strm)
{
switch (Type)
{
case varNull: strm << "(null)"; break;
case varInt: strm << intValue; break;
case varDouble: strm << dblValue; break;
}
}
};
class Interface
{
public:
virtual ~Interface() {}
virtual Variant GimeMeTheValue(void) = 0;
};
class TakeInt : public Interface
{
public:
Variant GimeMeTheValue(void)
{
return Variant(10);
}
};
class TakeDouble : public Interface
{
public:
Variant GimeMeTheValue(void)
{
return Variant(3.14);
}
};
std::ostream& operator<<(std::ostream &strm, const Variant &v)
{
v.writeTo(strm);
return strm;
}
int main()
{
Interface * obj;
obj = new TakeInt();
cout << obj->GimeMeTheValue() << endl; // It's 10, thank you
delete obj;
obj = new TakeDouble();
cout << obj->GimeMeTheValue() << endl; // Oh it's 3.14, I love you c++
delete obj;
}
At the moment I'm dealing with a delightful legacy code class implementing polymorphism by switch-case:
class LegacyClass {
public:
enum InitType {TYPE_A, TYPE_B};
void init(InitType type) {m_type=type;}
int foo() {
if (m_type==TYPE_A)
{
/* ...A-specific work... */
return 1;
}
// else, TYPE_B:
/* ...B-specific work... */
return 2;
}
/** Lots more functions like this **/
private:
InitType m_type;
};
I'd like to refactor this to proper polymorphism, e.g.:
class RefactoredClass {
public:
virtual ~RefactoredClass(){}
virtual int foo()=0;
};
class Class_ImplA : public RefactoredClass {
public:
virtual ~Class_ImplA(){}
int foo() {
/* ...A-specific work... */
return 1;
}
};
class Class_ImplB : public RefactoredClass {
public:
virtual ~Class_ImplB(){}
int foo() {
/* ...B-specific work... */
return 2;
}
};
Unfortunately, I have one crucial problem: due to optimization and architectural considerations, within a primary use of LegacyClass, I cannot use dynamic allocation; the instance is a member of a different class by composition:
class BigImportantClass{
/* ... */
private:
LegacyClass m_legacy;
}
(In this example, BigImportantClass may be dynamically allocated, but the allocation needs to be in one continuous virtual segment, and a single new() call; I can't make further calls to new() in the BigImportantClass ctor or in subsequent initialization methods.)
Is there a good way to initialize a concrete implementation, polymorphically, without using new()?
My own progress so far: What I can do is provide a char[] buffer as a member of BigImportantClass, and somehow initialize a concrete member of RefactoredClass in that memory. The buffer would be large enough to accommodate all implementations of RefactoredClass. However, I do not know how to do this safely. I know the placement-new syntax, but I'm new to dealing with alignment (hence, warned off by the C++-FAQ...), and aligning generically for all concrete implementations of the RefactoredClass interface sounds daunting. Is this the way to go? Or do I have any other options?
Here's some code... just doing the obvious things. I don't use C++11's new union features, which might actually be a more structured way to ensure appropriate alignment and size and clean up the code.
#include <iostream>
template <size_t A, size_t B>
struct max
{
static const size_t value = A > B ? A : B;
};
class X
{
public:
X(char x) { construct(x); }
X(const X& rhs)
{ rhs.interface().copy_construct_at_address(this); }
~X() { interface().~Interface(); }
X& operator=(const X& rhs)
{
// warning - not exception safe
interface().~Interface();
rhs.interface().copy_construct_at_address(this);
return *this;
}
struct Interface
{
virtual ~Interface() { }
virtual void f(int) = 0;
virtual void copy_construct_at_address(void*) const = 0;
};
Interface& interface()
{ return reinterpret_cast<Interface&>(data_); }
const Interface& interface() const
{ return reinterpret_cast<const Interface&>(data_); }
// for convenience use of virtual members...
void f(int x) { interface().f(x); }
private:
void construct(char x)
{
if (x == 'A') new (data_) Impl_A();
else if (x == 'B') new (data_) Impl_B();
}
struct Impl_A : Interface
{
Impl_A() : n_(10) { std::cout << "Impl_A(this " << this << ")\n"; }
~Impl_A() { std::cout << "~Impl_A(this " << this << ")\n"; }
void f(int x)
{ std::cout << "Impl_A::f(x " << x << ") n_ " << n_;
n_ += x / 3;
std::cout << " -> " << n_ << '\n'; }
void copy_construct_at_address(void* p) const { new (p) Impl_A(*this); }
int n_;
};
struct Impl_B : Interface
{
Impl_B() : n_(20) { std::cout << "Impl_B(this " << this << ")\n"; }
~Impl_B() { std::cout << "~Impl_B(this " << this << ")\n"; }
void f(int x)
{ std::cout << "Impl_B::f(x " << x << ") n_ " << n_;
n_ += x / 3.0;
std::cout << " -> " << n_ << '\n'; }
void copy_construct_at_address(void* p) const { new (p) Impl_B(*this); }
double n_;
};
union
{
double align_;
char data_[max<sizeof Impl_A, sizeof Impl_B>::value];
};
};
int main()
{
{
X a('A');
a.f(5);
X b('B');
b.f(5);
X x2(b);
x2.f(6);
x2 = a;
x2.f(7);
}
}
Output (with my comments):
Impl_A(this 0018FF24)
Impl_A::f(x 5) n_ 10 -> 11
Impl_B(this 0018FF04)
Impl_B::f(x 5) n_ 20 -> 21.6667
Impl_B::f(x 6) n_ 21.6667 -> 23.6667
~Impl_B(this 0018FF14) // x2 = a morphs type
Impl_A::f(x 7) n_ 11 -> 13 // x2 value 11 copied per a's above
~Impl_A(this 0018FF14)
~Impl_B(this 0018FF04)
~Impl_A(this 0018FF24)
I implemented this using C++11 unions. This code seems to work under g++ 4.8.2, but it requires the -std=gnu++11 or -std=c++11 flags.
#include <iostream>
class RefactoredClass {
public:
virtual ~RefactoredClass() { }; // Linking error if this is pure. Why?
virtual int foo() = 0;
};
class RefactorA : RefactoredClass {
double data1, data2, data3, data4;
public:
int foo() { return 1; }
~RefactorA() { std::cout << "Destroying RefactorA" << std::endl; }
};
class RefactorB : RefactoredClass {
int data;
public:
int foo () { return 2; }
~RefactorB() { std::cout << "Destroying RefactorB" << std::endl; }
};
// You may need to manually create copy, move, &ct operators for this.
// Requires C++11
union LegacyClass {
RefactorA refA;
RefactorB refB;
LegacyClass(char type) {
switch (type) {
case 'A':
new(this) RefactorA;
break;
case 'B':
new(this) RefactorB;
break;
default:
// Rut-row
break;
}
}
RefactoredClass * AsRefactoredClass() { return (RefactoredClass *)this; }
int foo() { return AsRefactoredClass()->foo(); }
~LegacyClass() { AsRefactoredClass()->~RefactoredClass(); }
};
int main (void) {
LegacyClass A('A');
LegacyClass B('B');
std::cout << A.foo() << std::endl;
std::cout << B.foo() << std::endl;
return 0;
}
Somebody should have made an answer by now...so here's mine.
I'd recommend using a union of char array and one of the biggest integer types:
union {
char refactored_class_buffer[ sizeof RefactoredClass ];
long long refactored_class_buffer_aligner;
};
I also strongly recommend putting an assert or even an if(check) throw; into your factory so that you never, ever, exceed the size of your buffer.
If the data is the same for each case, and you're only changing behaviuor, you don't need to allocate in your core - this is basically a strategy pattern using singleton strategies. You end up using polymorphism in your logic, but not in your data.
class FooStrategy() {
virtual int foo(RefactoredClass& v)=0;
}
class RefactoredClass {
int foo() {
return this.fooStrategy(*this);
}
FooStrategy * fooStrategy;
};
class FooStrategyA : public FooStrategy {
//Use whichever singleton pattern you're happy with.
static FooStrategyA* instance() {
static FooStrategyA fooStrategy;
return &fooStrategy;
}
int foo(RefactoredClass& v) {
//Do something with v's data
}
}
//Same for FooStrategyB
Then when you create a RefactoredClass you set its fooStrategy to FooStrategyA::instance().
My use is pretty complicated. I have a bunch of objs and they are all passed around by ptr (not reference or value unless its an enum which is byval). At a specific point in time i like to call CheckMembers() which will check if each member has been set or is null. By default i cant make it all null because i wouldnt know if i set it to null or if it is still null bc i havent touch it since the ctor.
To assign a variable i still need the syntax to be the normal var = p; var->member = new Type;. I generate all the classes/members. So my question is how can i implement a property like feature where i can detect if the value has been set or left as the default?
I am thinking maybe i can use C++ with CLR/.NET http://msdn.microsoft.com/en-us/library/z974bes2.aspx but i never used it before and have no idea how well it will work and what might break in my C++ prj (it uses rtti, templates, etc).
Reality (edit): this proved to be tricky, but the following code should handle your requirements. It uses a simple counter in the base class. The counter is incremented once for every property you wish to track, and then decremented once for every property that is set. The checkMembers() function only has to verify that the counter is equal to zero. As a bonus, you could potentially report how many members were not initialized.
#include <iostream>
using namespace std;
class PropertyBase
{
public:
int * counter;
bool is_set;
};
template <typename T>
class Property : public PropertyBase
{
public:
T* ptr;
T* operator=(T* src)
{
ptr = src;
if (!is_set) { (*counter)--; is_set = true; }
return ptr;
}
T* operator->() { return ptr; }
~Property() { delete ptr; }
};
class Base
{
private:
int counter;
protected:
void TrackProperty(PropertyBase& p)
{
p.counter = &counter;
counter++;
}
public:
bool checkMembers() { return (counter == 0); }
};
class OtherObject : public Base { }; // just as an example
class MyObject : public Base
{
public:
Property<OtherObject> x;
Property<OtherObject> y;
MyObject();
};
MyObject::MyObject()
{
TrackProperty(x);
TrackProperty(y);
}
int main(int argc, char * argv[])
{
MyObject * object1 = new MyObject();
MyObject * object2 = new MyObject();
object1->x = new OtherObject();
object1->y = new OtherObject();
cout << object1->checkMembers() << endl; // true
cout << object2->checkMembers() << endl; // false
delete object1;
delete object2;
return 0;
}
There are a number of ways to do this, with varying tradeoffs in terms of space overhead. For example, here's one option:
#include <iostream>
template<typename T, typename OuterClass>
class Property
{
public:
typedef void (OuterClass::*setter)(const T &value);
typedef T &value_type;
typedef const T &const_type;
private:
setter set_;
T &ref_;
OuterClass *parent_;
public:
operator value_type() { return ref_; }
operator const_type() const { return ref_; }
Property<T, OuterClass> &operator=(const T &value)
{
(parent_->*set_)(value);
return *this;
}
Property(T &ref, OuterClass *parent, setter setfunc)
: set_(setfunc), ref_(ref), parent_(parent)
{ }
};
struct demo {
private:
int val_p;
void set_val(const int &newval) {
std::cout << "New value: " << newval << std::endl;
val_p = newval;
}
public:
Property<int, demo> val;
demo()
: val(val_p, this, &demo::set_val)
{ }
};
int main() {
demo d;
d.val = 42;
std::cout << "Value is: " << d.val << std::endl;
return 0;
}
It's possible to get less overhead (this has up to 4 * sizeof(void*) bytes overhead) using template accessors - here's another example:
#include <iostream>
template<typename T, typename ParentType, typename AccessTraits>
class Property
{
private:
ParentType *get_parent()
{
return (ParentType *)((char *)this - AccessTraits::get_offset());
}
public:
operator T &() { return AccessTraits::get(get_parent()); }
operator T() { return AccessTraits::get(get_parent()); }
operator const T &() { return AccessTraits::get(get_parent()); }
Property &operator =(const T &value) {
AccessTraits::set(get_parent(), value);
return *this;
}
};
#define DECL_PROPERTY(ClassName, ValueType, MemberName, TraitsName) \
struct MemberName##__Detail : public TraitsName { \
static ptrdiff_t get_offset() { return offsetof(ClassName, MemberName); }; \
}; \
Property<ValueType, ClassName, MemberName##__Detail> MemberName;
struct demo {
private:
int val_;
struct AccessTraits {
static int get(demo *parent) {
return parent->val_;
}
static void set(demo *parent, int newval) {
std::cout << "New value: " << newval << std::endl;
parent->val_ = newval;
}
};
public:
DECL_PROPERTY(demo, int, val, AccessTraits)
demo()
{ val_ = 0; }
};
int main() {
demo d;
d.val = 42;
std::cout << "Value is: " << (int)d.val << std::endl;
return 0;
}
This only consumes one byte for the property struct itself; however, it relies on unportable offsetof() behavior (you're not technically allowed to use it on non-POD structures). For a more portable approach, you could stash just the this pointer of the parent class in a member variable.
Note that both classes are just barely enough to demonstrate the technique - you'll want to overload operator* and operator->, etc, as well.
Here's my temporary alternative. One that doesn't ask for constructor parameters.
#include <iostream>
#include <cassert>
using namespace std;
template <class T>
class Property
{
bool isSet;
T v;
Property(Property&p) { }
public:
Property() { isSet=0; }
T operator=(T src) { v = src; isSet = 1; return v; }
operator T() const { assert(isSet); return v; }
bool is_set() { return isSet; }
};
class SomeType {};
enum SomeType2 { none, a, b};
class MyObject
{
public:
Property<SomeType*> x;
Property<SomeType2> y;
//This should be generated. //Consider generating ((T)x)->checkMembers() when type is a pointer
bool checkMembers() { return x.is_set() && y.is_set(); }
};
int main(int argc, char * argv[])
{
MyObject* p = new MyObject();
p->x = new SomeType;
cout << p->checkMembers() << endl; // false
p->y = a;
cout << p->checkMembers() << endl; // true
delete p->x;
delete p;
}