在编译时检查 class 在 C++ 中是否有基数 class
Check if the class has any base class in C++ in compile time
我想使用 C++ 中的类型实用程序检查 class X
是否具有 任何 基 class。
例如:
class X : public Y
{
}
static_assert(std::has_base_class<X>::value, "") // OK
但是:
class X
{
}
static_assert(std::has_base_class<X>::value, "") // Failed
标准库中有没有我想象中的has_base_class
?谢谢!
如评论中所述,您无法在标准 C++ 中完全做到这一点。您从 std 库中获得的最接近的是 std::is_base_of
,但它用于测试特定的基数 class。
但如前所述 here GCC has std::tr2::bases
(and std::tr2::direct_bases
) that solves your question for a generic "has any base" assertion. These came from the N2965 proposal and unfortunately was rejected 对于标准 C++。
下面的示例代码展示了如何使用此 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;
}
我想使用 C++ 中的类型实用程序检查 class X
是否具有 任何 基 class。
例如:
class X : public Y
{
}
static_assert(std::has_base_class<X>::value, "") // OK
但是:
class X
{
}
static_assert(std::has_base_class<X>::value, "") // Failed
标准库中有没有我想象中的has_base_class
?谢谢!
如评论中所述,您无法在标准 C++ 中完全做到这一点。您从 std 库中获得的最接近的是 std::is_base_of
,但它用于测试特定的基数 class。
但如前所述 here GCC has std::tr2::bases
(and std::tr2::direct_bases
) that solves your question for a generic "has any base" assertion. These came from the N2965 proposal and unfortunately was rejected 对于标准 C++。
下面的示例代码展示了如何使用此 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;
}