我试图使用一种方法,允许自动启用强类型枚举类的位掩码操作符。以下是示例的头文件和cpp文件。
可以在此处查看:https://www.justsoftwaresolutions.co.uk/files/bitmask_operators.hpp 和 https://www.justsoftwaresolutions.co.uk/files/testbitmask.cpp 在testbitmask.cpp中的方法适用于一切在同一个命名空间下的情况。但我想将SFINAE代码与其他类的使用分开放置在不同的命名空间中。可以在这里进行查看:https://wandbox.org/permlink/05xXaViZT3MVyiBl。
这将导致在主函数中找不到重载的运算符。显式调用函数可以解决问题(
如果我们将特化移动到
可以在此处查看:https://www.justsoftwaresolutions.co.uk/files/bitmask_operators.hpp 和 https://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++中是否可能实现期望的方法?
using
,并且理想情况下不希望在头文件中使用using ONE::operator|
,因为它非常通用。我可以将枚举类包装在另一个命名空间中,并在其中使用它。如果有其他方法,我会再等一天,但我相信没有了。 - singhh23std
的operator ""s
使用类似。 - Jarod42