1

如果你operator <<为 C++11 定义了一个enum class,那么你可以成功地将它与 Boost 的单元测试库一起使用。

但是,如果您将enum classa 放入内部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);
}
4

1 回答 1

1

如果要使用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);
}
于 2015-11-24T02:58:30.680 回答