垫一个C ++结构的二的幂 [英] Pad a C++ structure to a power of two

查看:144
本文介绍了垫一个C ++结构的二的幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一些C ++ code为嵌入式系统。在I / O接口code使用要求每个消息(以字节为单位)的大小为二的幂。眼下,code做这样的事情(在几个地方):

I'm working on some C++ code for an embedded system. The I/O interface the code uses requires that the size of each message (in bytes) is a power of two. Right now, the code does something like this (in several places):

#pragma pack(1)
struct Message
{
   struct internal_
   {
      unsigned long member1;
      unsigned long member2;
      unsigned long member3;
      /* more members */
   } internal;
   char pad[64-sizeof(internal_)];
};
#pragma pack()

我试图编译在64位的Fedora code首次,其中是64位。在这种情况下,的sizeof(内部_)大于64,则数组大小恩pression下溢,编译器抱怨说,数组太大。

I'm trying to compile the code on a 64-bit Fedora for the first time, where long is 64-bits. In this case, sizeof(internal_) is greater than 64, the array size expression underflows, and the compiler complains that the array is too large.

在理想情况下,我希望能够写一个宏,将采取结构的大小,并以圆形结构的大小到的功率在编译时评估填充数组的大小要求两项。

Ideally, I'd like to be able to write a macro that will take the size of the structure and evaluate at compile time the required size of the padding array in order to round the size of the structure out to a power of two.

我看了看位操作黑客页面,但我不'知道是否有任何的技术有真的可以在宏来实现在编译时进行评估。

I've looked at the Bit Twiddling Hacks page, but I don't know if any of the techniques there can really be implemented in a macro to be evaluated at compile time.

这个问题的任何其他解决办法?或者我应该延续的问题,只是改变了神奇的64到128神奇?

Any other solutions to this problem? Or should I perpetuate the problem and just change the magical 64 to a magical 128?

推荐答案

使用的模板元程序。 (编辑回应评论)。

Use a template metaprogram. (Edited in response to comment).

#include <iostream>
#include <ostream>
using namespace std;

template <int N>
struct P
{
    enum { val = P<N/2>::val * 2 };
};

template <>
struct P<0>
{
    enum { val = 1 };
};

template <class T>
struct PadSize
{
    enum { val = P<sizeof (T) - 1>::val - sizeof (T) }; 
};

template <class T, int N>
struct PossiblyPadded
{
    T       payload;
    char    pad[N]; 
};

template <class T>
struct PossiblyPadded<T, 0>
{
    T       payload;
};

template <class T>
struct Holder : public PossiblyPadded<T, PadSize<T>::val>
{
};


int main()
{
    typedef char Arr[6];

    Holder<Arr> holder;
    cout << sizeof holder.payload << endl;

    // Next line fails to compile if sizeof (Arr) is a power of 2
    // but holder.payload always exists
    cout << sizeof holder.pad << endl;
}

这篇关于垫一个C ++结构的二的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆