c++ - 模板解析 - operator<< not found with boost-test

标签 c++ templates boost-test

下面的代码工作正常:

#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<<上面定义的模板。为什么这没有发生/如何解决?

最佳答案

编辑:查看评论,这是 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 );
}

https://godbolt.org/z/xoW-IJ

否则它不会为您的实现寻找正确的命名空间。很确定这是 ADL:https://en.cppreference.com/w/cpp/language/adl

关于c++ - 模板解析 - operator<< not found with boost-test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53530198/

相关文章:

javascript - meteor JS : Callback after template helper was updated

c++ - Lambda 表达式作为类模板参数

c++ - 对 DLL 中的非导出类进行单元测试

c++ - GCC Address Sanitizer - 将库函数列入黑名单(特别是 boost::test)

c++ - 具有 200GB 可用内存的 Bad Alloc c++

c++ - 错误 : two or more data types in declaration of main?

c++ - 主要跳过功能?

c++ - 移动 C++ 项目,atlplus.h 中的错误

c++ - 如何避免使用已知函数参数的 lambda 函数?

c++ - 有没有办法使用 Boost Test 测试非类型模板?