gpt4 book ai didi

c++ - 如何知道传递给函数的参数是 C++ 中的类、 union 还是枚举?

转载 作者:太空狗 更新时间:2023-10-29 20:47:49 24 4
gpt4 key购买 nike

我想为所有枚举定义一个运算符<<,以计算值并打印它是一个像这样的枚举:

代码:

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/

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