Creating an Array Initializer from a Tuple or Variadic Template Parameters
Variadic templates offer a solution to the need for automatic offset calculation in array initialization. By representing each element as an identifier and its size, a sequence can be created that drives the calculation of offsets.
A Layout structure is employed to hold the entries:
<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...> {};</code>
Each entry has an identifier and a type or size:
<code class="cpp">template<typename Key, Key identifier, typename Data> struct Entry {};</code>
To create a processed entry, we extend the concept:
<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; };</code>
Usage looks like this:
<code class="cpp">Layout< FooEnum, Entry< FooEnum, eFoo, char[10] >, Entry< FooEnum, eFoo2, double > > layout;</code>
After finding a prepend implementation that adds elements to the front of a tuple, Layout
The above is the detailed content of How do you calculate automatic array offsets using variadic templates in C ?. For more information, please follow other related articles on the PHP Chinese website!