1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
#include <iostream>
#include <concepts>
#include <ranges>
#include <numeric>
#include <vector>
#include <list>
template < typename A, typename B > concept accumulatable =
requires( A a, B b ) { { a += b } -> std::same_as<A&> ; } ;
template < std::ranges::input_range RANGE, typename T >
requires accumulatable< T, std::ranges::range_value_t<RANGE> >
T accum( const RANGE& range, const T& init_val )
{
return std::accumulate( std::ranges::begin(range), std::ranges::end(range), init_val ) ;
}
int main()
{
int a[] { 0, 14, 82, 5, 14 } ;
std::cout << accum( a, 1.5 ) << '\n' ; // 116.4
std::vector b { 0, 14, 82, 5, 14 } ;
std::cout << accum( b, 600L ) << '\n' ; // 715
std::list<std::string> c { "abc", "defgh", "ijkl", "mnopqr", "stuvwxyz" } ;
std::cout << accum( c, std::string( "letters: " ) ) << '\n' ; // letters: abcdefghijklmnopqrstuvwxyz
}
| |