#include <boost/test/included/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test1)
{
std::optional<int> opt1(10);
BOOST_TEST(t == 11);
std::optional<long> opt2(11);
BOOST_CHECK_EQUAL(opt1, opt2);
}
Is there any way to make boost test print (in code: BOOST_TEST) std
types? overloading operator<<
has to be in the namespace std
to be found by ADL and extending std
is forbidden. The only thing mentioned in boost's documentation is about UDTs and the solution also relies on ADL since it emphasizes on adding the custom function boost_test_print_type
in the same namespace as the UDT.
Regarding the suggested duplicate
I'm not sure. How would a thin wrapper, proposed in the duplicate, would work? Does that mean that I would have to convert to the wrapper in each test case before each assertion instead of directly using the standard type (optional)? If so, that is not what I'm looking for and undesired!
Here's a solution based on a wrapper template. I think it's far from ideal, but it should work as expected.
template <class T>
struct PrintableOpt {
std::optional<T> value;
};
The necessary operator overloads would be
template <class T>
std::ostream& operator << (std::ostream& os, const PrintableOpt<T>& opt)
{
if (opt.value)
return os << *opt.value;
else
return os << "std::nullopt";
}
template <class T, class U>
bool operator == (const PrintableOpt<T>& lhs, const PrintableOpt<U>& rhs)
{
return lhs.value && rhs.value && *lhs.value == *rhs.value;
}
template <class T, class U>
bool operator != (const PrintableOpt<T>& lhs, const PrintableOpt<U>& rhs)
{
return !(lhs == rhs);
}
and for convenience, here are two helper functions to construct the wrapper instances:
template <class T>
auto printable(T&& opt)
{
return PrintableOpt<T>{std::forward<T>(opt)};
}
template <class T>
auto printable(std::optional<T>& opt)
{
return PrintableOpt<T>{opt};
}
The test would now look like this:
BOOST_AUTO_TEST_CASE(test1)
{
std::optional<int> opt1(10);
BOOST_TEST(printable(opt1) == printable(11));
std::optional<long> opt2(11);
BOOST_CHECK_EQUAL(printable(opt1), printable(opt2));
}