Re: Automatically create initializer lists
Am 22.11.2012 06:28, schrieb fmatthew5876:
Is it possible to create a variable length initializer list from an
constant expression and fill the elements of the list with some
pattern?
Basically what I want to do is this:
struct Vec2 {
Vec2(float x, float y);
enum { size = 2; }
}
struct Vec3 {
Vec3(float x, float y, float z);
enum { size = 3; }
}
template <typename T> foo() {
T v SOME_COMPILE_TIME_MAGIC(T::size);
}
Where SOME_COMPILE_TIME_MAGIC(2) = {0, 1}
and SOME_COMPILE_TIME_MAGIC(3) = {0, 1, 2}
Basically calling the T() constructor for 2 or 3 parameters as needed.
OK, the following approach does *literally* what you are asking for,
but I'm cheating in one detail:
//------------
template<int...> struct indices {};
template<int I, class IndexTuple, int N>
struct make_indices_impl;
template<int I, int... Indices, int N>
struct make_indices_impl<I, indices<Indices...>, N>
{
typedef typename make_indices_impl<I + 1, indices<Indices..., I>,
N>::type type;
};
template<int N, int... Indices>
struct make_indices_impl<N, indices<Indices...>, N>
{
typedef indices<Indices...> type;
};
template<int N>
struct make_indices : make_indices_impl<0, indices<>, N> {};
template<typename T>
struct maker
{
template<int... I>
constexpr static T _(indices<I...>)
{
return T{I...};
}
};
template<typename T, int N>
constexpr T make_braced()
{
return maker<T>::_(typename make_indices<N>::type{});
}
#define SOME_COMPILE_TIME_MAGIC(N) = make_braced<decltype(v), N>()
//------------
My more serious recommendation would change your code to
template <typename T> void foo()
{
T v = make_braced<T, T::size>();
}
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]