gpt4 book ai didi

c++11 - 枚举类和全局运算符~重载

转载 作者:行者123 更新时间:2023-12-04 14:28:04 32 4
gpt4 key购买 nike

考虑以下代码:

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 就在这里,作用域枚举,又名 enum class不会隐式转换为 int 或其他任何内容。通过扩展,它们没有内置 operator~ ,所以你需要显式转换:

#include <iostream>
#include <type_traits>

enum class E { val };

int main () {
std::cout << ~std::underlying_type<E>::type(E::val);
}

通过删除您的 struct D和全局 operator~ , clang 给出了很好的错误。这是一个明显的错误 operator~(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 的引用的自由函数运算符。

关于c++11 - 枚举类和全局运算符~重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23108590/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com