J
Johannes Schaub (litb)
This is not legal. It would cause problems because auto is deduced byMichael said:I want to implement a jump table but don't want to give names to the
functions/functors jumped into. For example, I want the following:
extern int foo();
auto jump_table[] = {
[](int a, int b) {return a + b;},
[](int a, int b) {return a - b;},
[](int a, int b) {return a * b;},
[](int a, int b) {return a / b;} /* more functions will be added later
[*/
}; /* Is this legal? */
putting the declaration into an imaginary function template, and "T
jump_table[]" would be handled like a pointer parameter. The Standard rules
for array declarators at 8.3.4:
"if the type of the identiï¬er of D contains the auto type-speciï¬er, the
program is ill-formed".
Notice that anyway each lambda has an uniq type, so this cant work at all.
However work is underway to make them convert to a "int(*)(int,int)" so you
can use
identity<int(int,int)>::type *jump_table[] = {
[](int a, int b) { ... },
[](int a, int b) { ... },
...
};
int main() {
int x = foo();
jump_table[x](1, 2);
}
In particular, I don't want to pollute the namespace by giving names to
functions/functors that is used once only. (I can do this in Java by using
anonymous classes, but not in C++ (at least C++0x))
Why not use std::function<int(int,int)> ?
std::function<int(int,int)> jump_table[] = {
[](int a, int b) { ... },
[](int a, int b) { ... },
...
};