BOOST_CHECK_EQUAL with a pair <int, int> and a custom operator <<

When trying to execute BOOST_CHECK_EQUAL (pair, pair) gcc does not find the stream operator for the pair, despite its declaration. The funny thing is that std :: out finds a statement.

 ostream& operator<<(ostream& s, const pair<int,int>& p) { s << '<' << p.first << ',' << p.second << '>'; return s; } BOOST_AUTO_TEST_CASE(works) { pair<int,int> expected(5, 5); pair<int,int> actual (5, 5); std::cout << expected << std::endl; std::cout << actual << std::endl; BOOST_CHECK(actual == expected); } BOOST_AUTO_TEST_CASE(no_work) { pair<int,int> expected(5, 5); pair<int,int> actual (5, 5); BOOST_CHECK_EQUAL(actual, expected); } 

This does not compile with an error:

 ... instantiated from here ../boost-atp/release/include/boost/test/test_tools.hpp:326:9: error: no match for 'operator<<' in 'ostr << t' 
+7
source share
3 answers

Entering operator<< in std as Remus' answer is undefined behavior in a C ++ 14 project (section N4296: 17.6.4.2.1). Boost provides a hook ( used by this answer ), and you can write:

 namespace boost { namespace test_tools { template<typename T,typename U> struct print_log_value<std::pair<T, U> > { void operator()(std::ostream& os, std::pair<T, U> const& pr) { os << "<" << std::get<0>(pr) << "," << std::get<1>(pr) << ">"; } }; } } 

print_log_value is a template, so if you do not declare a template value, for example pair<T,U> , you need to write something like:

 template<> struct print_log_value<MyType>{ /* implementation here*/ }; 

Edit

If you are using boost 1.59 or later, you need to use the boost::test_tools::tt_detail . That is, the code should run:

 namespace boost { namespace test_tools { namespace tt_detail { 
+7
source

Try putting the statement in the std namespace :

 namespace std { ostream& operator<<(ostream& s, const pair<int,int>& p) { s << '<' << p.first << ',' << p.second << '>'; return s; } } 

Update: maybe that's why

+9
source

I was looking for something similar, a way to configure the output string to print integers in hexadecimal. Injecting the statement into the std namespace will work, but every BOOST_CHECK in my test will be printed in hexadecimal format.

So I introduced some custom operators in the boost namespace that I could control with some global bools.

See my answer here boost-check-fails-to-compile-operator-for-custom-types .

0
source

All Articles