c++boostboost-rangeboost-iterators

c++ boost ranges: any_range and transformed adaptor


I am trying to wrap a boost range that uses the boost transformed adapter into a boost any range, but this does not seem to work. I constructed a minimal example to illustrate.

std::vector<int> myInts = { 1,2,3,4,5 };
boost::any_range<double,boost::forward_traversal_tag,double> range =
    myInts | boost::adaptors::transformed( []( int x ) { return static_cast<double>( x ); } );

for ( double x : range )
    std::cout << x << "\n"; 

In release mode, my VS2015 compiler keeps telling me 'returning address of local variable or temporary'. The code also fails to perform correctly when executed. In debug mode everything is fine.

I think that somehow the any_range fails to understand that the transformed adaptor returns by value, even though I explicitly set the Reference template parameter to double instead of the default double&.

What am I doing wrong with the any_range? (Using boost 1.64.0)


Solution

  • You need to change your range declaration to boost::any_range<const double, boost::forward_traversal_tag, const double>, as the type deduction system needs to realize your range is read-only.