c 11 – 枚举类和全局运算符〜重载

前端之家收集整理的这篇文章主要介绍了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错误报告中减少:
http://gcc.gnu.org/bugzilla/show_bug.cgi?id=60852

这是未减少的测试用例:

#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:

For a unary operator @ with an operand of a type whose cv-unqualified
version is T1,[…],three sets of candidate functions,designated
member candidates,nonmember
candidates and built-in candidates,are constructed as follows:

结束:

However,if no operand has a class type,only those non-member
functions in the lookup set that have a first parameter of type T1 or
reference to (possibly cv-qualified) T1”,when T1 is an enumeration
type,are candidate functions.

总而言之,因为E是非类型的,所以只考虑采用E或E的引用的自由函数运算符.

原文链接:https://www.f2er.com/c/110775.html

猜你在找的C&C++相关文章