Using auto in a lambda function

后端 未结 4 1595
野性不改
野性不改 2020-12-13 17:22
#include 
#include 

void foo( int )
{
}

int main()
{
  std::vector< int > v( { 1,2,3 } );

  std::for_each( v.begin(), v.end()         


        
相关标签:
4条回答
  • 2020-12-13 18:10

    The type of the lambda needs to be known before the compiler can even instantiate std::for_each. On the other hand, even if it were theoretically possible, that auto could only be deduced after for_each has been instantiated by seeing how the functor is invoked.

    If at all possible, forget about for_each, and use range-based for loops which are a lot simpler:

    for (int it : v) { 
       foo(it + 5); 
    }
    

    This should also cope nicely with auto (and auto& and const auto&).

    for (auto it : v) { 
       foo(it + 5); 
    }
    
    0 讨论(0)
  • 2020-12-13 18:17

    C++14 allows lambda function (Generic lambda function) parameters to be declared with the auto.

    auto multiply = [](auto a, auto b) {return a*b;};
    

    For details: http://en.cppreference.com/w/cpp/language/lambda

    0 讨论(0)
  • 2020-12-13 18:19

    auto keyword does not work as a type for function arguments, in C++11. If you don't want to use the actual type in lambda functions, then you could use the code below.

     for_each(begin(v), end(v), [](decltype(*begin(v)) it ){
           foo( it + 5);         
     });
    

    The code in the question works just fine in C++ 14.

    0 讨论(0)
  • 2020-12-13 18:19

    This was discussed briefly by Herb Sutter during an interview. Your demand for auto arguments is in fact no different from demanding that any function should be declarable with auto, like this:

    auto add(auto a, auto b) -> decltype(a + b) { return a + b; }
    

    However, note that this isn't really a function at all, but rather it's a template function, akin to:

    template <typename S, typename T>
    auto add(S a, T b) -> decltype(a + b) { return a + b; }
    

    So you are essentially asking for a facility to turn any function into a template by changing its arguments. Since templates are a very different sort of entity in the type system of C++ (think of all the special rules for templates, like two-phase look-up and deduction), this would be radical design change with unforeseeable ramifications, which certainly isn't going to be in the standard any time soon.

    0 讨论(0)
提交回复
热议问题