1

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);
}
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 に答える