help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: #pragma pack doesn't work with template classes


From: Guy Harrison
Subject: Re: #pragma pack doesn't work with template classes
Date: Tue, 29 Jun 2004 17:38:57 -0000
User-agent: KNode/0.7.2

Matthias Hoffrichter wrote:

> Hi,
> 
> i'm using g++ (GCC) 3.3.1 (mingw special 20030804-1).
> 
> I used #pragma pack(push, 1) to set the alignment of my class members to
> one byte.

First off, I don't know the answer. The reason for that is because I don't
use such features.
 
> It works fine for normal classes but for template classes it seems as if
> it is ignored. Here is my code:
> 
> #include <iostream>
> 
> #pragma pack(push, 1)
> 
> class Test1
> {
> private:
>      char member1_;
>      long member2_;
> };
> 
> template<class T> class Test2
> {
> private:
>      char member1_;
>      long member2_;
> };

The above hints of a design problem in a non-portable module. Either
write...

long member2_;
char member1_;

..because you know the architecture and how it will be aligned, or...

char member1_;
char dummy[3];
long member2_;

...if initialisers come into play.
 
> #pragma pack(pop)
> 
> int main()
> {
>      std::cout << sizeof(Test1) << std::endl;
>      std::cout << sizeof(Test2<int>) << std::endl;
> }
> 
> Output is:
> 
> 5
> 8
> 
> With Visual C++ .NET 7.1 I got my desired result:
> 
> 5
> 5
> 
> Is this a bug? Or what is the reason for this behaviour?

I *think* (but am in no way sure) that it's depreciated.
 
> (I know that this problem can be solved by adding __attribute__
> ((__packed__)) to the member variables.)

Use that if you must. Essentially what you have is a raw data. Don't try and
attach C++ to it. Write the binary "portablility" layer then map (kludge)
that onto the C++ interface. Better still, fix both programs. Modify the
original program such that it can export a textfile. Have the new one
import it. Leave the compilers to optimise internal
representation /datafiles as they see fit.


-- 
Guy Harrison


reply via email to

[Prev in Thread] Current Thread [Next in Thread]