如果你operator <<
为 C++11 定义了一个enum class
,那么你可以成功地将它与 Boost 的单元测试库一起使用。
但是,如果您将enum class
a 放入内部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);
}