我正在尝试实现 std::is_enum
.到目前为止,这是我的代码:
mẫu
struct is_enum {
static bool value;
};
mẫu
bool is_enum::value = false;
template
struct is_enum {
static bool value;
};
template
bool is_enum::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’
谁能向我解释我在哪里犯了错误?是我的错还是编译器的错?提前致谢。
biên tập:如果完全错误,那我该如何纠正呢?
Để ý:我使用的是 g++ -o .cpp
实现这一点的最佳方法是使用编译器魔法,我相信大多数实现都是这样做的。
例如,这里是 libc++ 对 gcc >= 4.3 和任何 __has_feature(is_enum)
的编译器的实现。 1
template struct _LIBCPP_VISIBLE is_enum
: public integral_constant {};
对于所有其他编译器,libc++ 会:
template struct _LIBCPP_VISIBLE is_enum
: public integral_constant::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 Ví dụis_union
.但是,可以重写该条件,使其不需要编译器魔法。正如 Johannes Schaub 指出的那样,这可以通过将 union 和类的单独检查替换为两者的单独检查来完成。
<子>1。据我所知只有 clang 工具 __has_feature
,很遗憾。
<子> 2。有趣的是,libc++ 确实有 is_union
的版本。和 is_class
不使用编译器内在函数,但因此它们为 union 类型提供了错误的结果。但是它们的错误结果是互补的,所以 libc++ 的 is_enum
的后备实现提供准确的结果。
子>子>
Tôi là một lập trình viên xuất sắc, rất giỏi!