Creating an API / metaprogramming DSL for static initialization of a layout description

99封情书 提交于 2019-12-02 03:43:55

问题


I need to create a C++ metaprogramming DSL/API to describe generic data layouts. I want to have the data structure descriptions initialized statically (i.e. no dynamic memory allocation, preferably allocation in the ROM section).

I'm not yet very familiar with C++11 features but I'm aware you can do a lot more about initializing (statically) than the old standard provided.

I'm looking for a solution that makes it easy for a client to describe the data layout using some kind of 'basic' DataItemDescriptor like this:

template
    < typename ItemIdType
    , typename OffsetType = unsigned int
    >
struct DataItemDescBase
{
    const ItemIdType id;
    const OffsetType offset;
    const size_t size;

    DataItemDescBase(ItemIdType id_, OffsetType offset_, size_t size_)
    : id(id_)
    , offset(offset_)
    , size(size_)
    {
    }
};

template
    < typename DataType
    , typename ItemIdType
    , typename OffsetType = unsigned int
    >
struct DataItemDesc
: public DataItemDescBase<ItemIdType,OffsetType>
{
    typedef DataType DataTypeSpec;
    typedef ItemIdType IdTypeSpec;

    DataItemDesc(ItemIdType id_, OffsetType offset_)
    : DataItemDescBase(id_,offset,sizeof(DataTypeSpec))
    {
    }
};

and use s.th. like

enum MyDataItemId
{
   MyDataItem1 ,
   MyDataItem2 ,
   MyDataItem3 ,
}

std::array<DataItemDescBase<MyDataItemId>,3> dataLayoutDesc =
      { add_dataitem_desc<int>(MyDataItem1) ,
        add_dataitem_desc<unsigned short>(MyDataItem2) ,
        add_dataitem_desc<char[15]>(MyDataItem3) ,
      };

to let a client define it's concrete data layout structure (note that I've intended to calculate the necessary offset values also during compile time somehow).

I think type safety for the correlation of the id's and their associated types can be provided using some extra static checks (and 'binding' definitions from the client side). This is something I've already realized in some different context.

Can anyone lead me into the right direction or show samples how to do this using C++11 initialization features and meta-programming techniques?

来源:https://stackoverflow.com/questions/18242003/creating-an-api-metaprogramming-dsl-for-static-initialization-of-a-layout-desc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!