加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:38:31 所属栏目:百科 来源:网络整理
导读:请考虑以下代码: 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 ~makeRhs();};enum class E;int main () { return HE::value; } 这是有效
请考虑以下代码:
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的引用的自由函数运算符.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读