作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想为所有枚举定义一个运算符<<,以计算值并打印它是一个像这样的枚举:
代码:
enum AnyEnum{A,B,C};
AnyEnum enm = A;
cout << enm <<endl;
输出:
This is an enum which has a value equal to 0
我知道通过使用 is_enum 结构对 Boost 库执行此操作的方法。但我不明白它是如何工作的。所以这就是为什么,总的来说,我对如何识别可验证对象是类类型、 union 类型还是枚举(在编译时)很感兴趣。
最佳答案
确定类类型你可以使用成员指针存在的事实
template<typename A, typename B>
struct issame { };
template<typename A>
struct issame<A, A> { typedef void type; };
template<typename> struct tovoid { typedef void type; };
template<typename T, typename = void>
struct isclass { static bool const value = false; };
template<typename C>
struct isclass<C, typename tovoid<int C::*>::type> {
static bool const value = true;
};
您无法检测 union 类和非 union 类的区别。至少我不知道怎么做,boost 也不知道。
我认为检测枚举可以通过确保 T
不是类、函数或整数类型,然后尝试分配给整数类型来工作。你可以
template<typename E, typename = void>
struct isenum {
struct No { char x; };
struct Yes { No n1; No n2; };
struct nullsink {};
static No checkI(nullsink*); // accept null pointer constants
static Yes checkI(...);
static Yes checkE(int);
static No checkE(...);
static bool const value = (sizeof(checkI(E())) == sizeof(Yes)) &&
(sizeof(checkE(E())) == sizeof(Yes));
};
// class
template<typename E>
struct isenum<E, typename tovoid<int E::*>::type> {
static bool const value = false;
};
// reference
template<typename R>
struct isenum<R&, void> {
static bool const value = false;
};
// function (FuntionType() will error out).
template<typename F>
struct isenum<F, typename issame<void(F), void(F*)>::type> {
static bool const value = false;
};
// array (ArrayType() will error out)
template<typename E>
struct isenum<E[], void> {
static bool const value = false;
};
template<typename E, int N>
struct isenum<E[N], void> {
static bool const value = false;
};
快速和肮脏的测试(适用于 GCC/clang/comeau):
enum A { };
struct B { };
typedef int &C;
typedef void D();
typedef int E;
typedef long F;
typedef int const G;
typedef int H[1];
template<typename T, bool E>
struct confirm { typedef char x[(T::value == E) ? 1 : -1]; };
int main() {
confirm< isenum<A>, true >();
confirm< isenum<B>, false >();
confirm< isenum<C>, false >();
confirm< isenum<D>, false >();
confirm< isenum<E>, false >();
confirm< isenum<F>, false >();
confirm< isenum<G>, false >();
confirm< isenum<H>, false >();
}
关于c++ - 如何知道传递给函数的参数是 C++ 中的类、 union 还是枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4705316/
我是一名优秀的程序员,十分优秀!