Boost测试失败,命名空间中有枚举类



如果您为C++11 enum class定义了operator <<,那么您可以将其成功地用于Boost的单元测试库。

但是,如果将enum class放入namespace中,Boost代码将不再编译。

为什么把enum class放在namespace里面会阻止它工作?它在两种方式下都能与std::cout一起工作,所以这肯定意味着operator <<是正确的吗?

以下是一些演示问题的示例代码:

// g++ -std=c++11 -o test test.cpp -lboost_unit_test_framework
#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE EnumExample
#include <boost/test/unit_test.hpp>
// Remove this namespace (and every "A::") and the code will compile
namespace A {
enum class Example {
    One,
    Two,
};
} // namespace A
std::ostream& operator<< (std::ostream& s, A::Example e)
{
    switch (e) {
        case A::Example::One: s << "Example::One"; break;
        case A::Example::Two: s << "Example::Two"; break;
    }
    return s;
}
BOOST_AUTO_TEST_CASE(enum_example)
{
    A::Example a = A::Example::One;
    A::Example b = A::Example::Two;
    // The following line works with or without the namespace
    std::cout << a << std::endl;
    // The following line does not work with the namespace - why?
    BOOST_REQUIRE_EQUAL(a, b);
}

如果要使用ADL,则需要在命名空间内定义运算符。

#include <iostream>
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE EnumExample
#include <boost/test/unit_test.hpp>
namespace A {
enum class Example {
    One,
    Two,
};

std::ostream& operator<< (std::ostream& s, Example e)
{
    switch (e) {
        case A::Example::One: s << "Example::One"; break;
        case A::Example::Two: s << "Example::Two"; break;
    }
    return s;
}
} // namespace A
BOOST_AUTO_TEST_CASE(enum_example)
{
    A::Example a = A::Example::One;
    A::Example b = A::Example::Two;
    // The following line works with or without the namespace
    std::cout << a << std::endl;
    // The following line does not work with the namespace - why?
    BOOST_REQUIRE_EQUAL(a, b);
}

最新更新