跨命名空间的基于SFINAE的运算符重载

3
我试图使用一种方法,允许自动启用强类型枚举类的位掩码操作符。以下是示例的头文件和cpp文件。
可以在此处查看:https://www.justsoftwaresolutions.co.uk/files/bitmask_operators.hpphttps://www.justsoftwaresolutions.co.uk/files/testbitmask.cpp 在testbitmask.cpp中的方法适用于一切在同一个命名空间下的情况。但我想将SFINAE代码与其他类的使用分开放置在不同的命名空间中。可以在这里进行查看:https://wandbox.org/permlink/05xXaViZT3MVyiBl
#include <type_traits>

namespace ONE {
    template<typename E>
    struct enable_bitmask_operators{
        static const bool enable=false;
    };

    template<typename E>
    inline typename std::enable_if<enable_bitmask_operators<E>::enable,E>::type
    operator|(E lhs,E rhs){
        typedef typename std::underlying_type<E>::type underlying;
        return static_cast<E>(
            static_cast<underlying>(lhs) | static_cast<underlying>(rhs));
    }
}

namespace TWO {
    enum class A{ x=1, y=2};
}

namespace ONE {
    template<>
    struct enable_bitmask_operators<TWO::A>{
        static const bool enable=true;
    };
}

int main(){
    TWO::A a1 = TWO::A::x | TWO::A::y;
}

这将导致在主函数中找不到重载的运算符。显式调用函数可以解决问题(TWO::A a1 = ONE::operator|(TWO::A::x , TWO::A::y);),但这显然不是期望的功能。
如果我们将特化移动到namespace ONE中,编译器会抛出一个错误:error: declaration of 'struct ONE::enable_bitmask_operators<TWO::A>' in namespace 'TWO' which does not enclose 'ONE' 。我想知道在C++中是否可能实现期望的方法?
1个回答

4

您的函数无法被ADL找到,您可以添加一些using来允许使用它:

using ONE::operator|;
TWO::A a1 = TWO::A::x | TWO::A::y;

演示

using namespace ONE; 可能也是一种替代方案。


我认为这是可以接受的 - 不希望在每个使用枚举的cpp中都需要using,并且理想情况下不希望在头文件中使用using ONE::operator|,因为它非常通用。我可以将枚举类包装在另一个命名空间中,并在其中使用它。如果有其他方法,我会再等一天,但我相信没有了。 - singhh23
1
这与 stdoperator ""s 使用类似。 - Jarod42

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接