简体   繁体   中英

BOOST_CHECK fails to compile operator<< for custom types

I wrote this really trivial class so that it's clear what my problem is:

class A
{
public:
    int x;
    A(int y) {x=y;}
    bool operator==(const A &other) const {return x==other.x;}
};

Now, if I define A first(1) and A second(1), it would seem natural to me that BOOST_CHECK_EQUAL(first, second) should pass. However, I got 50 errors when trying to do this, the first one sounds like: no math for operator << in ostr << t which is somewhere in the boost code... Other tests work just fine, comparing known types or even pointers, but there is something different that appears to happen with class objects.

There are three ways I have identified to solve the problem with operator<< .

The first way is to provide an operator<< for your type. This is needed because when boost_check_equal fails, it also logs the failure by calling operator<< with the objects. See the verbose addendum after the break to see how this is actually accomplished. It's harder than it might seem.

The second way is to not do the logging I just mentioned. You can do this by #definine ing BOOST_TEST_DONT_PRINT_LOG_VALUE . To disable logging for just one test, you might surround the test in question with this #define , then immediately #undef it:

#define BOOST_TEST_DONT_PRINT_LOG_VALUE
BOOST_CHECK_EQUAL (first, second);
#undef BOOST_TEST_DONT_PRINT_LOG_VALUE

The third way is to sidestep the need for an operator<< that works with your type by not comparing one item to another, but just checking a bool:

BOOST_CHECK (first == second);

Select your preferred method.


My preference is the first, but implementing that is suprisingly challenging. If you simply define an operator<< in global scope, it won't work. I think the reason for this is because of a problem with name resolution. One popular suggestion to fix this is to put the operator<< in the std namespace. This works, at least in practice on some compilers, but I don't like it because the Standard prohibits adding anything to the std namespace.

A better method I found is to implement a custom print_log_value class template specialization for your type. print_log_value is a class template useb by the Boost.Test internals to actually call the correct operator<< for the specified type. It delegates to an operator<< to do the heavy lifting. Specializing print_log_value for your custom types is officially supported by Boost [citation needed], and is accomplished thusly.

Assuming your type is called Timestamp (it is in my code), first define a global free operator<< for Timestamp :

static inline std::ostream& operator<< (std::ostream& os, const Mdi::Timestamp& ts)
{
    os << "Timestamp";
    return os;
}   

...and then provide the print_log_value specialization for it, delegating to the operator<< you just defined:

namespace boost { namespace test_tools {
template<>           
struct print_log_value<Mdi::Timestamp > {
void operator()( std::ostream& os,
    Mdi::Timestamp const& ts)
{
    ::operator<<(os,ts);
}
};                                                          
}}

Based on John Dibling 's answer I was looking for a way to dump integer values in HEX rather than decimal I came up with this approach:

// test_macros.h in my project
namespace myproject
{
namespace test
{
namespace macros
{
    extern bool hex;

    // context manager
    struct use_hex
    {
        use_hex()  { hex = true; }
        ~use_hex() { hex = false; }
    };

 }; // namespace
 }; // namespace
 }; // namespace

namespace boost
{
namespace test_tools
{

    // boost 1.56+ uses these methods

    template<>
    inline                                               
    void                                                 
    print_log_value<uint64>::                       
    operator()(std::ostream & out, const uint64 & t) 
    {                                                    
        if(myproject::test::macros::hex)                    
            out << ::boost::format("0x%016X") % t;           
        else 
            out << t;                                        
    }                                                    

namespace tt_detail
{

    // Boost < 1.56 uses these methods

    template <>
    inline
    std::ostream &
    operator<<(std::ostream & ostr, print_helper_t<uint64> const & ph )
    {
        if(myproject::test::macros::hex)
            return ostr << ::boost::format("0x%016X") % ph.m_t;

        return ostr << ph.m_t;
    }

}; // namespace
}; // namespace
}; // namespace

Now in my unit test case, I can turn on/off hex by setting the global static bool value, for example:

for(uint64 i = 1; i <= 256/64; ++i)
{
    if(i % 2 == 0) test::macros::hex = true;
    else           test::macros::hex = false;
    BOOST_CHECK_EQUAL(i+1, dst.pop());
}

And I get the behavior I was looking for:

test_foobar.cc(106): error in "test_foobar_51": check i+1 == dst.pop() failed [2 != 257]
test_foobar.cc(106): error in "test_foobar_51": check i+1 == dst.pop() failed [0x0000000000000003 != 0x0000000000000102]
test_foobar.cc(106): error in "test_foobar_51": check i+1 == dst.pop() failed [4 != 259]
test_foobar.cc(106): error in "test_foobar_51": check i+1 == dst.pop() failed [0x0000000000000005 != 0x0000000000000104]

Alternatively, I can use the context manager:

{
    test::macros::use_hex context;

    for(uint64 i = 1; i <= 4; ++i)
    {
        BOOST_CHECK_EQUAL(i + 0x200, i + 0x100);
    }
}

for(uint64 i = 1; i <= 4; ++i)
{
    BOOST_CHECK_EQUAL(i + 0x200, i + 0x100);
}

And hex output will only be used in that block:

test_foobar.cc(94): error in "test_foobar_28": check i + 0x200 == i + 0x100 failed [0x0000000000000201 != 0x0000000000000101]
test_foobar.cc(94): error in "test_foobar_28": check i + 0x200 == i + 0x100 failed [0x0000000000000202 != 0x0000000000000102]
test_foobar.cc(94): error in "test_foobar_28": check i + 0x200 == i + 0x100 failed [0x0000000000000203 != 0x0000000000000103]
test_foobar.cc(94): error in "test_foobar_28": check i + 0x200 == i + 0x100 failed [0x0000000000000204 != 0x0000000000000104]
test_foobar.cc(100): error in "test_foobar_28": check i + 0x200 == i + 0x100 failed [513 != 257]
test_foobar.cc(100): error in "test_foobar_28": check i + 0x200 == i + 0x100 failed [514 != 258]
test_foobar.cc(100): error in "test_foobar_28": check i + 0x200 == i + 0x100 failed [515 != 259]
test_foobar.cc(100): error in "test_foobar_28": check i + 0x200 == i + 0x100 failed [516 != 260]

This is a supplement to the excellent answer from John Dibling . The problem seems to be that there needs to be an output operator in the right namespace. So if you have a global output operator<< defined, then you may avoid this error (at least with Visual Studio 2015, aka vc14, and boost 1.60) by defining another one in the boost::test_tools::tt_detail namespace that forwards to the global operator. This minor tweak enables one to avoid a strange and more verbose specialization of the print_log_value class. Here is what I did:

namespace boost {
namespace test_tools {
namespace tt_detail {
std::ostream& operator<<(std::ostream& os, Mdi::Timestamp const& ts)
{
    return ::operator<<(os, ts);
}
}  // namespace tt_detail
}  // namespace test_tools
}  // namespace boost

While it has been three years since this question and answer have been posted, I have not seen this discussed clearly in the Boost.Test documentation .

There is a clean way starting Boost 1.64 to log user defined types via the customization points . The full documentation of this feature can be found here .

An example from the documentation is given below. The idea is to define the function boost_test_print_type for the type you want to print, and to bring this function into the test case (found via ADL):

#define BOOST_TEST_MODULE logger-customization-point
#include <boost/test/included/unit_test.hpp>

namespace user_defined_namespace {
  struct user_defined_type {
      int value;

      user_defined_type(int value_) : value(value_)
      {}

      bool operator==(int right) const {
          return right == value;
      }
  };
}

namespace user_defined_namespace {
  std::ostream& boost_test_print_type(std::ostream& ostr, user_defined_type const& right) {
      ostr << "** value of user_defined_type is " << right.value << " **";
      return ostr;
  }
}

BOOST_AUTO_TEST_CASE(test1)
{
    user_defined_namespace::user_defined_type t(10);
    BOOST_TEST(t == 11);

    using namespace user_defined_namespace;
    user_defined_type t2(11);
    BOOST_TEST(t2 == 11);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM