c++ - Can a non-captured variable be shadowed by a lambda parameter? -


i have code looks - it's heavily simplified snippet compiles , exhibits same behaviour:

template <typename tfunc> float floatselect( const float in_value, tfunc&& predicate) {   return std::forward<tfunc>(predicate)(in_value) ? in_value : 0.0f; };  void displayfloatselect() {   const float value = floatselect(     -1.0f,     [] (const float value) { return value > 0.0f; }   );    std::cout << value << std::endl; } 

with -wshadow enabled compiler emits following warning (as seen here):

12 : warning: declaration shadows local variable [-wshadow]  [] (const float value) { return value > 0.0f; }  ^  10 : note: previous declaration here  const float value = floatselect(  ^ 

which not helpful - understand shadowing variable lambda not capture anything, should fine here.

what missing?

yes, non-captured variable can shadowed lambda parameter.

in particular case of lambda in op, might argue inner declaration of value not shadow scope of outer declaration because lambda has no captures. nonetheless, outer value can seen inside body of lambda, because body of lambda still inside scope of enclosing block:

(c++14 §5.1.2/p.7): lambda-expression’s compound-statement yields function-body (8.4) of function call operator, for purposes of name lookup (3.4), determining type , value of (9.3.2) , transforming idexpressions referring non-static class members class member access expressions using (*this) (9.3.1), the compound-statement considered in context of lambda-expression.

the odr-use of non-captured variable outer scope error, possible lambda without captures make use of name defined in outer scope if not odr-use (and in such case, variable not captured.) in particular, possible use const variables outer scope:

const int = 20; int f = ([](){return + 3;})(); 

so though lambda has no captures, explicit argument named i shadow outer i. (see http://coliru.stacked-crooked.com/a/006f5f20cca841d5; might want try enabling -wshadow.)

since -wshadow precisely intended reveal sort of ambiguous name usage, doesn't seem surprising triggers warning in case in op.

-wshadow not enabled either -wall nor -wextra precisely because going warn don't care about.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -