gpt4 book ai didi

c++ - is_enum 实现

转载 作者:IT老高 更新时间:2023-10-28 22:12:32 33 4
gpt4 key购买 nike

我正在尝试实现 std::is_enum .到目前为止,这是我的代码:

template<typename T>
struct is_enum {
static bool value;
};

template<typename T>
bool is_enum<T>::value = false;

template<enum E>
struct is_enum {
static bool value;
};

template<enum E>
bool is_enum<E>::value = true;

此代码会导致错误。更准确地说:

g++ -std=c++0x -Wall -o "enum2" "enum2.cpp" (in directory: /home/aristophanes/Desktop/C++)
Compilation failed.
enum2.cpp:11:15: error: use of enum ‘E’ without previous declaration
enum2.cpp:3:10: error: template parameter ‘class T’
enum2.cpp:12:8: error: redeclared here as ‘int E’
enum2.cpp:16:15: error: use of enum ‘E’ without previous declaration
enum2.cpp:17:14: error: ‘E’ was not declared in this scope
enum2.cpp:17:15: error: template argument 1 is invalid
enum2.cpp:17:18: error: template declaration of ‘bool value’

谁能向我解释我在哪里犯了错误?是我的错还是编译器的错?提前致谢。

编辑:如果完全错误,那我该如何纠正呢?

注意:我使用的是 g++ -o <file> <file>.cpp

最佳答案

实现这一点的最佳方法是使用编译器魔法,我相信大多数实现都是这样做的。

例如,这里是 libc++ 对 gcc >= 4.3 和任何 __has_feature(is_enum) 的编译器的实现。 1

template <class _Tp> struct _LIBCPP_VISIBLE is_enum
: public integral_constant<bool, __is_enum(_Tp)> {};



对于所有其他编译器,libc++ 会:

template <class _Tp> struct _LIBCPP_VISIBLE is_enum
: public integral_constant<bool, !is_void<_Tp>::value &&
!is_integral<_Tp>::value &&
!is_floating_point<_Tp>::value &&
!is_array<_Tp>::value &&
!is_pointer<_Tp>::value &&
!is_reference<_Tp>::value &&
!is_member_pointer<_Tp>::value &&
!is_union<_Tp>::value &&
!is_class<_Tp>::value &&
!is_function<_Tp>::value > {};

其中一些其他类型特征仍然需要编译器魔法。2 例如is_union .但是,可以重写该条件,使其不需要编译器魔法。正如 Johannes Schaub 指出的那样,这可以通过将 union 和类的单独检查替换为两者的单独检查来完成。

<子>1。据我所知只有 clang 工具 __has_feature ,很遗憾。
<子> 2。有趣的是,libc++ 确实有 is_union<T> 的版本。和 is_class<T>不使用编译器内在函数,但因此它们为 union 类型提供了错误的结果。但是它们的错误结果是互补的,所以 libc++ 的 is_enum<T> 的后备实现提供准确的结果。

关于c++ - is_enum 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11316912/

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