On Aug 12, 4:45 am, red floyd <no.spam.h...@example.comwrote:
Ed wrote:
[...]
I give a improper sample code here. But the question is clear I think.
Yes. You need something like:
union SemanticValue
{
double d ;
int i ;
std::string s ;
} ;
With, obviously, some information elsewhere which tells you
which one (if any) is active.
If I want to make a class as a member of union, how can I
make it.
Change the sample code.
template<typename P>
class Vector1
{
public:
P mValue;
public:
Vector1 (P);
Vector1 (const Vector1 vec_);
}
template<typename P>
class Vector3
{
public:
union
{
Vector1<Pxyz[3];
struct
{
Vector1<Px;
Vector1<Py;
Vector1<Pz;
};
}
}
That looks bad. You do know that if you assign something to x,
you can no longer read xyz, and vice versa.
You can't. I believe you can only put a POD inside a union.
Practically. (I forget the exact list of restrictions, but
they're pretty close to making the object a POD.)
What you can do (at some cost in terms of programming effort) is
create a discriminated union. Something along the lines of:
class SemanticValue
{
public:
enum Type { typeDouble, typeInt, typeString } ;
explicit SemanticValue( double d ) ;
explicit SemanticValue( int i ) ;
explicit SemanticValue( std::string const& s ) ;
SemanticValue( SemanticValue const& other ) ;
~SemanticValue() ;
SemanticValue& operator=( SemanticValue const& other ) ;
Type type() const ;
operator double() const ;
operator int() const ;
operator std::string() const ;
private:
Type myType ;
union {
double d ;
int i ;
unsigned char s[ sizeof( std::string ) ] ;
// This supposes that std::string doesn't
// have stricter alignment requirements
// than double or int. Probably a safe
// bet.
} myData ;
} ;
SemanticValue::SemanticValue(
std::string const& s )
: myType( typeString )
{
new ( myData.s ) std::string( s ) ;
}
SemanticValue::~SemanticValue()
{
if ( myType == typeString ) {
reinterpret_cast< std::string* >( myData.s )
->std::string::~string() ;
}
}
and so on. (With manual type checking in the copy constructor
and assignment operator as well.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34