c++capturevalarray

Processing Valarrays


Thanks for the attention in advance.

So i'm processing a valarray from STL, i'm curious about capturing values using a Closure.

Why i can't pass values by reference. Taking as instance the following code :

#include <iostream>
#include <valarray>
#include <functional>



int main()
{

    std::valarray<int>arr={1,2};
    std::valarray<int>arr2;


    arr2=arr.apply([](int a){return a+=2;}); 

      /* arr2=arr.apply([&](int a){return a+=2;}); 
   error: no matching for call to std::valarray<int>::apply(main()::<lambda(int)> */


    for(int x: arr2){
        std::cout<<x;
    }

    return 0;
}

Thank you !


Solution

  • Unlike almost any other standard library function that takes a form of predicate or other callable object, the std::valarray<T>::apply function actually only takes an actual pointer to a function, and not using templates to accept anything callable.

    A capture-less lambda can be converted to a pointer to a function, like what the apply function needs. But if you use captures in your lambda then that's not possible anymore.