以下代码可以正常工作:
#define BOOST_TEST_MODULE TestFoo
#include <boost/test/unit_test.hpp>
#include <boost/dynamic_bitset.hpp>
#include <string>
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T> &v)
{
os << "[ ";
for ( const T& elem : v )
os << elem << ' ';
return os << ']';
}
typedef boost::dynamic_bitset<> BS;
static const std::vector<BS> foo = { BS(std::string("101")) };
BOOST_AUTO_TEST_CASE( test_foo )
{
BOOST_CHECK_EQUAL( foo[0], foo[0] );
}
但是,当我用替换测试用例时
BOOST_AUTO_TEST_CASE( test_foo )
{
BOOST_CHECK_EQUAL( foo, foo );
}
然后编译器不再找到operator<<
:
/usr/include/boost/test/test_tools.hpp:326:14: error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘const std::vector<boost::dynamic_bitset<> >’)
我希望编译器实例化上面定义的operator<<
模板。为什么这没有发生/如何解决?
答案 0 :(得分:1)
编辑:查看评论,这是UB-似乎没有解决该问题的“好方法”。
将您的op<<
包裹在namespace std {...}
#include <boost/dynamic_bitset.hpp>
#include <boost/test/unit_test.hpp>
namespace std { // THIS LINE
template <typename T, typename... Rest>
std::ostream& operator<<(std::ostream& os, const std::vector<T, Rest...> &v)
{
os << "[ ";
for ( const T& elem : v )
os << elem << ' ';
os << ']';
return os;
}
} // THIS LINE
typedef boost::dynamic_bitset<> BS;
static const std::vector<BS> foo = { BS(std::string("101")) };
BOOST_AUTO_TEST_CASE( test_foo )
{
BOOST_CHECK_EQUAL( foo, foo );
}
否则,它没有在正确的命名空间中查找实现。可以确定这是ADL:https://en.cppreference.com/w/cpp/language/adl