473,387 Members | 1,812 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Put User Defined Class into Union

Ed
Hi, guys,
A big rock blocks my way.

I know that to put a user defined class with copy constructor,
override operator method, etc, can not be placed into Union. But I
have to.

I am refactoring an old system with template feature. If there is no
way, that means I had to pay additional work to re-implementation.

I am wondering if there is some tricks to fix it?

Say, I have a simple template class:

template<typename P>
class Vector1
{
public:
P mValue;

public:
Vector1 (P);
Vector1 (const Vector1 vec_);

}

template<typename P>
class Vector3
{
public:
union
{
Vector1<Pp1;
Vector1<Pp2;
Vector1<Pp3;
}

}
Thanks!
Aug 11 '08 #1
3 1519
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
Aug 12 '08 #2
Ed
On Aug 12, 5:30 pm, James Kanze <james.ka...@gmail.comwrote:
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.
If x was change, I think it will not impact the xyz reading, because
their addresses are the same.
Vector3<floatpoint;
point.x = 1.0f;
point.y = 1.0f;
point.z = 1.0f;

// If my thinking is right, the following assert should be true.
assert( point.x == point.xyz[0] );
>
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:james.ka...@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
Thanks for all of your suggestions. I get a lot.
Aug 13 '08 #3
On Aug 13, 9:20 am, Ed <seah...@gmail.comwrote:
On Aug 12, 5:30 pm, James Kanze <james.ka...@gmail.comwrote:
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.
If x was change, I think it will not impact the xyz reading,
because their addresses are the same.
Maybe. Maybe not. The language makes no guarantees.
Vector3<floatpoint;
point.x = 1.0f;
point.y = 1.0f;
point.z = 1.0f;
// If my thinking is right, the following assert should be true.
assert( point.x == point.xyz[0] );
According to the language, that is undefined behavior. It might
work, or it might not. You can't even predict what might
happen.

--
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
Aug 13 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: jonnychang | last post by:
What is the purpose of using union in this class? Class A { public: union { int age; char * name; double amount; } };
4
by: iceColdFire | last post by:
Hi @all, I am trying to include struct and class objects in a union ,like class A{ int a; A(){} }; struct B {
2
by: Thomas Paul Diffenbach | last post by:
I'm trying to write a space efficient string (nul terminated array of char), storing the characters directly unless the number of characters is too large to be so stored, and storing a pointer to...
1
by: Ghost | last post by:
Hi all, I wrote a program in C# and now I have to "translate" it i visual C++ (MFC) using .NET, but I had a little problem: *ERRORS* error C3181: 'CTestDlg' : invalid operand for __typeof,...
27
by: Randy | last post by:
Is there a way to override operators for user-defined types (e.g., typedefs) rather than class types? I'm trying to override the extractor operator for a user-defined enumeration type but...
13
by: zacariaz | last post by:
I need a specific non existing data type, and it seems that i am not smart enough to write the code my self, so if anyone will take the time to do it for me, they are more than welcome and i will...
1
by: zaeminkr | last post by:
I have a question about type conversion function for user defined type. I have two classes class DRect { private : double x0; double y0;
4
by: zaeminkr | last post by:
I got a good answer here I have still confusing part. I have two very simple classes class DRect { private : double x0, y0, x1, y1; public : DRect(double a, double b, double c, double d) :...
4
by: Steven Simpson | last post by:
Stefan Ram wrote (in "More than one language in a page"): Is this a new trend of user-agent writers (Microformats, and now Google) staking claims on the @class namespace? I'm surely not the only...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.