3

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?

Grimkin
  • 107
  • 5
  • function template cannot be passed. (use `auto` in parameter is also a function template ) – apple apple Dec 03 '22 at 13:16
  • I'm aware that this is a template, but I couldn't figure out the type I needed, so that's why I used this. Is there a parameter type that can be used here? – Grimkin Dec 03 '22 at 13:31

1 Answers1

1

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

apple apple
  • 10,292
  • 2
  • 16
  • 36
  • as a side note, declare as function object disables overload (in namespace) and ADL. it should be used with care. – apple apple Dec 03 '22 at 13:44