Lambda with patterns

I am currently doing some pattern exercises. I had the task of writing an implementation of the transformation algorithm. I have done the following:

template <class in, class out, class T>
out stransform(in b, in e, out d, T p(const T&)) {
    while (b != e) 
        *d++ = p(*b++);
    return d;
}

As with normal conversion, I have to call a predicate with an explicit type type

stransform(begin(vec1), end(vec1), back_inserter(vec2), predi<double>);

Now I came across C ++ 11 Lambdas and wanted to call my function as follows:

stransform(begin(vec1), end(vec1), back_inserter(vec2), [] (double x) ->double {return x * 10;} );

With this, I get a compiler error, which we choose type can not. This is something I donโ€™t understand, as I define type T in my lambda almost twice.

I also checked the original conversion function it works with. Then I checked the implementation of this and obviously implemented with a template class for the whole function. Is this the right way to implement pattern predicates?

+5
3

:

template <class in, class out, class UnaryPredicate>
out stransform(in b, in e, out d, UnaryPredicate p); 

, lambdas .

+13

T p(const T&) - , T . .

stransform (
    begin (vec1),
    end (vec1),
    back_inserter (vec2),
    [] (const double & x) -> double {
        return x * 10;
    });

. , , .

+2

, ,

: std::transform - , . ,

template<class InputIterator, class OutputIterator, class Functor>
OutputIterator
transform(InputIterator begin, InputIterator end, OutputIterator out, Functor f);

InputIterator, OutputIterator Functor . :

// function declaration
int increment(int);

int array[] = { 0, 1, 2, 3, 4 };
transform(std::begin(array), std::end(array), std::begin(array), increment);

InputIterator OutputIterator int*, Functor - int(*)(int), , , . , transform

template<typename InputIterator, typename OutputIterator, typename Functor>
OutputIterator
transform(InputIterator begin, InputIterator end, OutputIterator out, Functor f);

where the keyword typenamedescribes in more detail the nature of the template parameters: they are types of any nature.

+2
source

All Articles