- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我正在尝试实现 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/
我正在尝试实现 std::is_enum .到目前为止,这是我的代码: template struct is_enum { static bool value; }; template boo
我很感兴趣这件事在理论上是如何运作的。示例: #include #include enum foo { AAA, BBB }; typedef foo bar; struct sf
当我尝试编译时,G++编译器显示以下错误: C:\wx\include\wx\strvararg.h|350|error: 'is_enum' in namespace 'std' does not
MCVE: #include template bool func( typename std::enable_if::value, T >::type &t, int x ) { } enum c
我是一名优秀的程序员,十分优秀!