C++14 introduces generic lambdas,where you can specify the parameters as auto. We can pass variable of any type to these lambdas. But since C++ is a statically typed language, auto variables need to be ascertained i.e determined during or before compilation. So you might be wondering how the auto variables in generic lambdas can take any type or any combination of types. The answer is that the generic lambdas work very similar to the templates and they also use the same inference / deduction rules to determine the type as template type deduction.
If you run the code, you will see that id is 2 only for adder(a,b). This is because the version of the function was already instantiated before for adder(x,y). Also note that the type of const int, int, int&, int&&(i.e rValues) are all different. If you want to see the exact types, you can uncomment line 8, 11 and run the program. Also note the usage of decltype in the program.
Suppose we have a generic lambda which intends to forward it's parameters to another function. In generic lambdas, we do not have a typename T like we have in template functions. So how do we use std::forward<T>(variable) ? We utilize decltype.
The below program demonstrates perfect forwarding in generic lambdas using a (contrived) example.
If you run the code, you will see that id is 2 only for adder(a,b). This is because the version of the function was already instantiated before for adder(x,y). Also note that the type of const int, int, int&, int&&(i.e rValues) are all different. If you want to see the exact types, you can uncomment line 8, 11 and run the program. Also note the usage of decltype in the program.
Suppose we have a generic lambda which intends to forward it's parameters to another function. In generic lambdas, we do not have a typename T like we have in template functions. So how do we use std::forward<T>(variable) ? We utilize decltype.
The below program demonstrates perfect forwarding in generic lambdas using a (contrived) example.
Modern Effective C+ - Use decltype to forward auto parameters
Reviewed by zeroingTheDot
on
April 30, 2018
Rating:
No comments: