Skip to content

Instantly share code, notes, and snippets.

@ming4883
Created June 11, 2015 04:02
Show Gist options
  • Save ming4883/73dbaa0c9ca05bd1e6f2 to your computer and use it in GitHub Desktop.
Save ming4883/73dbaa0c9ca05bd1e6f2 to your computer and use it in GitHub Desktop.
Fill a static c-array with loop unroll support
// view the assembly output in https://goo.gl/VEyRNK or https://gcc.godbolt.org/#
#include <iostream>
using namespace std;
struct Array
{
template<typename T, int N>
struct Elem
{
static inline void set (T* array, T&& val)
{
array[N] = val;
Elem<T, N-1>::set (array, (T&&)val);
}
static inline void set (T* array, T val)
{
array[N] = val;
Elem<T, N-1>::set (array, val);
}
};
template<typename T>
struct Elem<T, 0>
{
static inline void set (T* array, T&& val)
{
array[0] = val;
}
static inline void set (T* array, T val)
{
array[0] = val;
}
};
template<typename T, int N>
static void fill (T (&array)[N], T&& val)
{
Elem<T, N-1>::set ((T*)array, val);
}
template<typename T, int N>
static int countof (T (&array)[N])
{
return N;
}
};
int main()
{
int array[10];
Array::fill (array, 4321);
for (int i = 0; i < Array::countof (array); ++i)
cout << array[i] << ", ";
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment