Creating Array Initializers from Tuple or Variadic Template Parameters
In order to create array initializers from tuple or variadic template parameters, a compile-time sequence needs to be established, which can be achieved through the use of variadic templates.
Template Declarations
First, define the following templates:
<code class="cpp">template<std::size_t offset, typename Key, typename... Entries> struct LayoutHelper { typedef std::tuple<> type; }; template<typename Key, typename... Entries> struct Layout:LayoutHelper<0, Key, Entries...> {}; template<typename Key, Key identifier, typename Data> struct Entry {};</code>
Layout Accumulation
To accumulate offsets, use a recursive helper function:
<code class="cpp">template<std::size_t offset, typename Key, Key id0, typename D0, typename... Entries> struct LayoutHelper<offset, Key, Entry<Key, id0, D0>, Entries...> { typedef typename prepend < ProcessedEntry< Key, id0, D0, offset > , typename LayoutHelper<offset+sizeof(D0), Key, Entries...>::type >::type type; };</code>
Usage
To use this technique, provide a layout specification using the following syntax:
<code class="cpp">Layout< FooEnum, Entry< FooEnum, eFoo, char[10] >, Entry< FooEnum, eFoo2, double > > layout;</code>
After unpacking the layout tuple, the resulting array can be used for accessing data at runtime.
The above is the detailed content of How to Create Array Initializers from Tuple or Variadic Template Parameters?. For more information, please follow other related articles on the PHP Chinese website!