lundi 27 février 2017

How to use bitmask_operators.hpp with namespace and classes

I want to use C++11 enum class as bitfields and find a nice approach here.

But I stuck, if my enum class declaration is not in global namespace but in custom namespace or inside of a class instead. E.g.:

#define ENABLE_BIT_OPERATORS(E) template<> struct enable_bitmask_operators<E> { static constexpr bool enable=true; };

// anonymous namespace
namespace {
enum class Ean {
    None = 0x00,
    Bit0 = 0x01,
    Bit1 = 0x02,
    Bit2 = 0x04,
    Bit3 = 0x08,
};
ENABLE_BIT_OPERATORS(Ean);
} // anonymous namespace

// custom namespace
namespace Custom {
enum class Ecn {
    None = 0x00,
    Bit0 = 0x01,
    Bit1 = 0x02,
    Bit2 = 0x04,
    Bit3 = 0x08,
};
ENABLE_BIT_OPERATORS(Ecn);
} // custom namespace

// inside class in global namespace
class MyclassGN {
public:
    enum class Ecgn {
        None = 0x00,
        Bit0 = 0x01,
        Bit1 = 0x02,
        Bit2 = 0x04,
        Bit3 = 0x08,
    };
    ENABLE_BIT_OPERATORS(Ecgn);
};

// inside class in anonymous namespace
namespace {
class MyclassAN {
public:
    enum class Ecan {
        None = 0x00,
        Bit0 = 0x01,
        Bit1 = 0x02,
        Bit2 = 0x04,
        Bit3 = 0x08,
    };
    ENABLE_BIT_OPERATORS(Ecan);
};
} // anonymous namespace

// inside class in custom namespace
namespace Custom {
class MyclassGN {
public:
    enum class Ecgn {
        None = 0x00,
        Bit0 = 0x01,
        Bit1 = 0x02,
        Bit2 = 0x04,
        Bit3 = 0x08,
    };
    ENABLE_BIT_OPERATORS(Ecgn);
};
} // custom namespace

This always gives me errors:

error: specialization of 'template<class E> struct enable_bitmask_operators' in different namespace

until I place my template specialization to the same namespace as the template enable_bitmask_operators in bitmask_operators.hpp is located (global namespace in this case).

But I want to have my specialization close to my enum class declaration.

In the mentioned article, this problem is also commented by Jay Miller and it seems that he provides a solution. But I failed to follow his hints to solve this in bitmask_operators.hpp.

Example code here.

Aucun commentaire:

Enregistrer un commentaire