lundi 23 novembre 2015

Boost test fails with enum classes inside namespaces

If you define an operator << for a C++11 enum class, then you can use it successfully with Boost's unit test library.

However if you put the enum class inside a namespace, the Boost code no longer compiles.

Why does putting the enum class inside a namespace stop it from working? It works fine with std::cout both ways so surely this means the operator << is correct?

Here is some sample code demonstrating the issue:

// 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);
}

Aucun commentaire:

Enregistrer un commentaire