I’m trying to chain a boost::adaptors::transformed (let’s call it map) to a boost::adaptors::filtered (let’s call it filter) – the idea is to map a fun that returns a “Maybe” (in my case, a std::pair<bool, T>) over a range and output only part of the results. My first implementation:
define BOOST_RESULT_OF_USE_DECLTYPE // enable lambda arguments for Boost.Range
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/adaptor/transformed.hpp>
struct OnlyEven
{
typedef int argument_type;
typedef std::pair<bool, int> result_type;
result_type operator()(argument_type x) const
{
std::cout << "fun: " << x << std::endl;
return std::make_pair(x % 2 == 0, x);
}
} only_even;
int main(int argc, char* argv[])
{
auto map = boost::adaptors::transformed;
auto filter = boost::adaptors::filtered;
int v[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto s = v | map(only_even) | filter([](std::pair<bool, int> x)->bool{ return x.first; });
for (auto i : s) {}
return 0;
}
When I run this, I get:
fun: 1
fun: 2
fun: 2
fun: 3
fun: 4
fun: 4
fun: 5
fun: 6
fun: 6
fun: 7
fun: 8
fun: 8
fun: 9
fun: 10
fun: 10
Every time the predicate is true, fun is called twice. Is this expected behavior? Am I doing something wrong, or is/was this a bug in Boost (I’m using 1.48)?
Edit: I tried this on the trunk version of Boost and it still happens.
First time it is called when passed to your filter – during increment.
Second time it is called in your range-based-for – during dereference. It does not cache result.
I.e., just passing thru range:
gives:
Check implementation of filter_iterator (filtered is based on it). It doesn’t do any caching.
filtered do not use knowladge where it’s input comes from.
Caching of result would require incresing size of filtered iterators. Just think where cached result should be stored. It should be copied into some member of filtered iterator.
So, basically, there is trade-off between space for caching and count of dereferencing.
EDIT: I have made proof-of-concept of cached_iterator which caches result of dereference, and invalidates it on each advancing. Also, I have made corresponding range adaptor.
Here how it is used:
You should place cached in chain where you want to cache result.
live demo
Output is: