问题
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