代码之家  ›  专栏  ›  技术社区  ›  bartop

STD:C++ 03替代:Aligndl存储

  •  0
  • bartop  · 技术社区  · 7 年前

    因为C++ 11有一个专用的模板结构 std::aligned_storage alignas 用于存储任何选定类型的对齐数据的关键字。我想知道是否可以为 STD:阿利格尼存储 这是在C++ 03中支持的。我唯一能想到的方法是创建适当的对齐( unsigned ) char 数组,但如何以正确的方式对齐对我来说是一个很大的未知数

    1 回复  |  直到 7 年前
        1
  •  3
  •   Dutow    7 年前

    可以实现 alignof 在C++ 03中,对于大多数类型,例如有一个很长的解释。 this page

    有了它,您可以使用一些模板专门化来使用具有这种对齐方式的存储类型:

    #include<iostream>
    
    struct alignment {};
    
    template<>
    struct alignment<1> {
      typedef char type;
      static const unsigned div_v=sizeof(type);
      static const unsigned add_v=div_v-1;
    };
    template<>
    struct alignment<2> {
      typedef short type;
      static const unsigned div_v=sizeof(type);
      static const unsigned add_v=div_v-1;
    };
    template<>
    struct alignment<4> {
      typedef int type;
      static const unsigned div_v=sizeof(type);
      static const unsigned add_v=div_v-1;
    };
    template<>
    struct alignment<8> {
      typedef double type;
      static const unsigned div_v=sizeof(type);
      static const unsigned add_v=div_v-1;
    };
    
    template<typename T>
    struct align_store {
      typedef alignment<__alignof(T)> ah;
    
      typename ah::type data[(ah::add_v + sizeof(T))/ah::div_v];
    };
    
    int main() {
      std::cout << __alignof(align_store<int>) << std::endl;
      std::cout << __alignof(align_store<double>) << std::endl;
    }