3

During testing when using c++ 11 I have used the following construct:

std::for_each( coll.begin(), coll.end(), 
    [ &obj, expRes ]( const value_type& val )
    {
       BOOST_CHECK_EQUAL( expRes, obj.someFunc( val ) );
    } );

I am currently working on a project where C++11 is not used and am I a looking for a way to generate a similar lambda expression, without having to create separate a function / functor.

I understand basic use of boost::phoenix to create lambdas, but I cannot think of a way to create a phoenix lambda that is capable of calling a boost::test macro.

The best I can come up with is:

template< typename T >
void MakeCheck( const T& lhs, const T& rhs )
{
    BOOST_CHECK_EQUAL( lhs, rhs );
}


/// inside some other function...
std::for_each( coll.begin(), coll.end(), 
    ph::bind( MakeCheck<bool>, true, 
              ph::bind( &MyClass::someFunc, obj, ph::arg_names::arg1 ) ) );

Unfortunately this approach looses the line number information of failed checks, since the macro BOOST_CHECK_EQUAL reports the line number of the macro, not the line number of the std::for_each call.

Is there a better way of creating a lambda that involves a macro call using 'boost::phoenix`?

mark
  • 7,381
  • 5
  • 36
  • 61

1 Answers1

1

Macros are always expanded first, so the only way to get the correct line number would be to:

  • not embed macros in templates
  • or extract any __LINE__, __FILE__, or other context sensitive macros from the template body by turning them into template parameters and wrap the top level expression (macro or template) with a macro using these extracted values.

It's probably not so difficult to refactor the boost code to include these modifications (about 4 levels of nested code), but that wouldn't be easy to maintain afterward.

didierc
  • 14,572
  • 3
  • 32
  • 52
  • 1
    perhaps this could be considered a bug in the boost library? – didierc Nov 07 '12 at 13:13
  • unfortunately manually expanding (or partially expanding) the BOOST_TEST macros does not get me any closer to the C++11 lambda expression. I would like to get rid of the separate template function altogether. – mark Nov 07 '12 at 14:10
  • sorry, I thought your problem was the wrong error location reported by the test macro. I'm afraid you won't get a C++11 lambda without C++11, macros cannot substitute for that feature. – didierc Nov 07 '12 at 14:15