The following simple code pattern is very common in graphics programming.
It creates an array of layers and loops over them.
struct Layer
{
int n;
void operator()(float value)
{
}
};
struct AnotherLayer
{
int n;
int m;
void operator()(float value)
{
}
};
void process_layers(Layer_t* layer, size_t size, float value)
{
for (size_t n = 0; n < size; ++n)
layer[n](value);
}
Layer a = {1};
Layer b = {2};
AnotherLayer c = {2,3};
typedef std::function < void (float) > Layer_t;
Layer_t layers [] = {a,b,c};
process_layers(layers, sizeof(layers)/sizeof(Layer), 100);
I would like to convert this to use varadic templates in c++11. Any ideas how I could do this. This is what I would like it to look like. Any ideas? Is this even possible?
template <int n>
struct Layer
{
void operator()(float value)
{
}
};
template <int n, int m>
struct AnotherLayer
{
void operator()(float value)
{
}
};
template <typename Layer1, typename Layer2, ...>
struct Layers //process_layers
{
void operator()(float value)
{
for (size_t n = 0; n < SIZEOF(Layer1,Layer2,...); ++n)
Layer[N]()(value);
}
};
Then I could do this.
typedef Layers<Layer<1>, Layer<2>, AnotherLayer<3,8> > funky_layer_t;
typedef Layers<Layer<4>, Layer<5>, Layer<5>, AnotherLayer<6,7> > standard_layer_t;
typedef Layers<funky_layer_t, standard_layer_t> awesome_layer_t;
awesome_layer_t()(100);
Note: with the second approach, all paramaters to construct layers are known at compile time.
The example you give is very simple to re-do with variadic templates.
Also notice that this avoids all the unnecessary copies in the original. (Though of course you could also avoid them just by doing
Layer layers[] = {{1},{2},{3}};)I’m not exactly sure how your later comments and code are related to running an operation over a collection of layers.
What exactly is the computation you want to perform at compile-time?
To adjust for the new example the
process()does not need to change at all, you only need to create a functor that can handle each type. (polymorphic lambdas would help here, but we’ll have to make due with an explicit functor type)Here’s your
awesome_layer_ttranscribed to correct variadic template syntax, but I still don’t see what you want to accomplish, so I can’t say if this is a good way to do it or not. This doesn’t actually call theoperator()s at compile-time, it only arranges to have a bunch of objects default constructed at runtime and thenoperator()called, again, at runtime.