代码之家  ›  专栏  ›  技术社区  ›  Henning Koehler

模板分辨率-运算符<<未通过boost测试找到

  •  0
  • Henning Koehler  · 技术社区  · 7 年前

    以下代码可以正常工作:

    #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<> >’)
    

    操作员<&书信电报; 上面定义的模板。为什么没有发生这种情况/如何修复?

    1 回复  |  直到 7 年前
        1
  •  1
  •   xaxxon    7 年前

    编辑:见评论,这是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