[英]Check if the class has any base class in C++ in compile time
I want to check whether the class X
has ANY base class using type utilities in C++.我想使用 C++ 中的类型实用程序检查 class
X
是否具有任何基础 class。
For example:例如:
class X : public Y
{
}
static_assert(std::has_base_class<X>::value, "") // OK
but:但:
class X
{
}
static_assert(std::has_base_class<X>::value, "") // Failed
Does anything like my imaginary has_base_class
exist in the standard library?标准库中是否存在像我想象的
has_base_class
之类的东西? Thanks!谢谢!
As mentioned in comments you can't do exactly this in standard C++.正如评论中提到的,您不能在标准 C++ 中完全做到这一点。 The closest you get from std library is
std::is_base_of
, but it is for testing a specific base class.您从 std 库中获得的最接近的是
std::is_base_of
,但它用于测试特定的基础 class。
But as mentioned here GCC has std::tr2::bases
(and std::tr2::direct_bases
) that solves your question for a generic "has any base" assertion.但正如这里提到的 GCC 有
std::tr2::bases
(和std::tr2::direct_bases
)可以解决您对通用“有任何基础”断言的问题。 These came from the N2965 proposal and unfortunately was rejected for std C++.这些来自N2965 提案,不幸的是被 std C++拒绝。
Here's a sample code showing how you can use this GCC extension to assert just what you want:这是一个示例代码,展示了如何使用此 GCC 扩展来断言您想要的内容:
#include <tr2/type_traits>
class B {};
class X : public B {};
static_assert(std::tr2::bases<X>::type::empty(),"X");
// doesn't compile because X bases tuple returned is not empty
class Y {};
static_assert(std::tr2::bases<Y>::type::empty(),"Y");
#include <iostream>
using namespace std;
int main() {
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.