简体   繁体   中英

How to declare a function, that takes a range

I want to declare a function, that gets a range as input, outputs a single number and use it directly with ranges::views::transform of the range-v3 library.

The following works but I have to use a lambda that doesn't really do anything.

int64_t getGroupValue( ranges::input_range auto&& group ) {
    return ranges::accumulate( group, 1ll, ranges::multiplies() );
}

int64_t calculateGroupSum( const std::vector<int>& data ) {
    using ranges::views::transform;
    using ranges::views::chunk;

    return ranges::accumulate(
        data
        | chunk( 3 )
        | transform( [] ( auto group ) { return getGroupValue( group ); })
        , 0ll);
}

I want to do the following:

int64_t calculateGroupSum( const std::vector<int>& data ) {
    using ranges::views::transform;
    using ranges::views::chunk;

    return ranges::accumulate(
        data
        | chunk( 3 )
        | transform( getGroupValue )
        , 0ll);
}

Is this somehow possible by using a different parameter type for getGroupValue() or do I have to use the lambda?

function template cannot be passed around.*

One way is wrap it inside lambda object as you already did, or you can write it as function object at first place.

struct getGroupValue_op{
    int64_t operator()( ranges::input_range auto&& group ) const{
        return ranges::accumulate( group, 1ll, ranges::multiplies() );
    }
} getGroupValue;

*it can work if the parameter has specific type, but it's not the case for range::views::transform

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM