Ok c++ gurus, I have been playing with lambdas so far and have been using them basically to pass a function to a function:
e.g.
auto myfunc = [](int &i) -> void {i = i+1;};
ApplyFunction(myfunc);
///////////////////////////////////////
template <typename Func> void ApplyFunction(Func lambda_func)
{
for (int n=0; n<10; n++)
{
int s=0;
lambda_func(s);
OutputInteger(s);
}
}
I now want to perform something considerably more funky (excuse the pun). I want to perform several (3 or so) lambda functions on a large number of elements, however the function to be used is not known ahead of time, and in each case the function chosen is from a selection:
Here's some pseudocode:
void DoStuff(eCol enum_col_func, eBright enum_bright_func)
{
auto func_colour;
auto func_brightness;
switch (enum_col_func)
{
case COL_RED:
func_colour = [](int &col) -> void {col = 10;};
break;
case COL_BLUE:
func_colour = [](int &col) -> void {col = 5;};
break;
}
switch (enum_bright_func)
{
case BRIGHT_FULL:
func_bright = [](int &br) -> void {br = 255;};
break;
case BRIGHT_MED:
func_bright = [](int &br) -> void {br = 127;};
break;
}
IterateElements(func_colour, func_bright);
}
////////////////////////////////////////////////////
template <typename CFunc, typename BFunc> void IterateElements(CFunc fcolour, BFunc fbrightness)
{
for (unsigned int n=0; n<10000; n++)
{
fcolour(m_Colour[n]);
fbrightness(m_Brightness[n]);
}
}
////////////////////////////////////////////////////
Now try not to get obsessed with the minutiae (or suggesting profiling etc), as this is just an example to try and illustrate the kind of problem I am attempting to solve.
It is essentially an optimisation issue. What I want to end up with, is a array of machine code functions for all possible combinations of IterateElements (compile time) so that when the tight loop is called there are:
- No branches
- No function pointers used
So the question is can I use lambdas to force the compiler to output each combination, and what would be the correct syntax? I know I can do it using macros, but this in itself would become quite verbose, and I would prefer to use the 'modern' method.
Just for illustration, in actual use there would be:
Function 1 (10 possibilities)
Function 2 (2 possibilities)
Function 3 (2 possibilities)
Function 4 (2 possibilities)
Function 5 (2 possibilities)
Thus 10 * 2 * 2 * 2 * 2 = 160 combinations, different versions of the loop function that I'd want in the executable.