operator <<
C++11 に対してを定義するenum class
と、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);
}