Alf P. Steinbach
unread,Sep 19, 2018, 5:11:57 PM9/19/18You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
The big selling point of the ranges library (possibly part of C++20) is
that instead of
sort( begin( v ), end( v ) );
... you can write just
ranges::sort( v );
... where the necessary qualification is the tiny cost of this goodness.
The ranges library also allows you to write very terse and concise 100%
inefficient and 100% cryptic code with apparent pipe expressions,
chained expressions, and whatnot, that in addition to the mentioned
inefficiency and quality of being cryptic, is so leading edge with
respect to compiler support that it's not portable until 202x.
* * *
A simple alternative to the ranges library's main advantage, is to just
define
// Careful, don't call with lvalue expression that has side effects.
#define $items( c ) std::begin( *&c ), std::end( c )
Then write e.g.
sort( $items( v ) );
If you don't like the formally non-standard $ then name it e.g. `ITEMS`.
The `*&c` in the definition helps to avoid using `$items` with a
function call as argument, it gives you an up-front error about that
function being called twice, instead of leaving the discovery of that
inadvertent error to testing. It's not 100% because one could have a
function returning a reference, in which case the compiler is happy with
taking the address. But it's not a correct usage guarantee, it's just
helping out (bigly) by guarding against /inadvertent/ incorrect use.
* * *
To deal with passing iterators from the result of a function call,
without introducing lots of very local named variables like
// Copy get_numbers() to the not assignment-compatible destination.
{
const auto& numbers = get_numbers();
copy( begin( numbers ), end( numbers ), begin( destination ) );
}
just define
#define $with( ... ) \
if( const auto& _ = __VA_ARGS__; !!&_ )
The `!!&_` avoids a possible warning about unused `_`.
Then write e.g.
$with( get_numbers() )
{
copy( $items( _ ), begin( destination ) );
}
And that can be useful also with e.g. mutexes and other RAII objects.
Cheers!,
- Alf