Home >Backend Development >C++ >Can C 0x Metaprogramming Techniques be Used to Programmatically Assign Values to Static Arrays at Compile Time?
Programmatically Generating Static Arrays at Compile Time in C
Given the ability to define static arrays at compile time in C , is it possible to programmatically assign their values using metaprogramming techniques?
Question 1: Programmatic Assignment of Array Values
Yes, using C 0x features, it is feasible to initialize array elements "programmatically" at compile time. Consider the following example:
template<unsigned... args> struct ArrayHolder { static const unsigned data[sizeof...(args)]; }; template<unsigned... args> const unsigned ArrayHolder<args...>::data[sizeof...(args)] = { args... };
Question 2: Selective Assignment of Array Values
Assuming the array contains recurring values with some exceptions, it is possible to selectively assign values programmatically:
template<size_t N, template<size_t> class F, unsigned... args> struct generate_array_impl { typedef typename generate_array_impl<N-1, F, F<N>::value, args...>::result result; }; template<template<size_t> class F, unsigned... args> struct generate_array_impl<0, F, args...> { typedef ArrayHolder<F<0>::value, args...> result; }; template<size_t N, template<size_t> class F> struct generate_array { typedef typename generate_array_impl<N-1, F>::result result; };
Usage for the array with recurring zeros except for elements 2 and 3:
template<size_t index> struct MetaFunc { enum { value = index == 2 || index == 3 ? index + 1 : 0 }; }; void test() { const size_t count = 7; typedef generate_array<count, MetaFunc>::result A; for (size_t i=0; i<count; ++i) std::cout << A::data[i] << "\n"; }
While these solutions are limited by the maximum template instantiation depth, they demonstrate the potential of C 0x for programmatic array creation and initialization.
The above is the detailed content of Can C 0x Metaprogramming Techniques be Used to Programmatically Assign Values to Static Arrays at Compile Time?. For more information, please follow other related articles on the PHP Chinese website!