c 11 – 枚举类和全局运算符?重载
请考虑以下代码:
struct D { template <class T> D (T); }; int operator~(const D &); template <typename T> T &make (); template <typename Rhs> struct H { static const int value = sizeof ~make<Rhs>(); }; enum class E; int main () { return H<E>::value; } 这是有效的C 11吗? Clang接受了它. Gcc给出了一个错误: % gcc -std=c++11 b.ii b.ii: In instantiation of ‘const int H<E>::value’: b.ii:16:28: required from here b.ii:11:35: error: no match for ‘operator~’ (operand type is ‘E’) static const int value = sizeof ~make<Rhs>(); 代码从gcc错误报告中减少: 这是未减少的测试用例: #include <boost/type_traits.hpp> #include <iostream> enum class E {}; int main() { std::cout << boost::has_complement<E>() << std::endl; } 解决方法
GCC就在这里,范围枚举,aka枚举类不会隐式转换为int或其他任何东西.通过扩展,它们没有内置运算符?,因此您需要显式转换:
#include <iostream> #include <type_traits> enum class E { val }; int main () { std::cout << ~std::underlying_type<E>::type(E::val); } 通过删除struct D和全局运算符?,clang给出了错误.这是一个明显的错误,因为运算符?(D)首先不是候选人: main.cpp:17:35: error: invalid argument type 'E' to unary expression static const int value = sizeof ~make<Rhs>(); 关于收集过载的规则§13.3.1.2:
结束:
总而言之,因为E是非类型的,所以只考虑采用E或E的引用的自由函数运算符. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |