简体   繁体   English

在编译时检查 class 是否在 C++ 中有任何基础 class

[英]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.

相关问题 C++ - 检测是编译时的第一个基类 - C++ - detect is first base class at compile time 编译时检查基类是否为“接口” - Compile time check whether a base class is “interface” C ++如何在编译时检查模板参数类的签名 - C++ how to check the signature of a template parameter class at compile time c ++编译时断言BASE是EXTENDED的基类并且具有相同的内存地址 - c++ compile time assert that BASE is base class of EXTENDED and have same memory address 编译时检查 class 从基础 class 继承并用作它 - Compile time check that a class inherits from a base class and use as it C++ 检查 class 是否源自模板基础 class; 具有完整的模板参数 - C++ Check if class derived from template base class; which has integral template parameters C ++编译类的子类的时间列表 - C++ Compile time list of subclasses of a class 如何在编译时检测C ++ 17中的类是否没有虚拟基础? - How to detect whether a class has no virtual base in C++17 at compile time? C ++:使用类型名作为基础的模板类中的函数调用编译时错误 - C++ : Function call Compile-Time Error from a Template Class using Typename as Base 在C ++中,为什么编译器在编译时不理解基类对象指向哪个对象? - in C++, why compiler does not understand which object is pointed by base class object at compile time?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM