How to query for all base classes of a class at compile time?
With std::is_base_of<A,B>::value
one can check if a class A
is a base class of
class B
. Is it also possible to query the compiler for all base classes of a class
B
, e.g., something like base_classes_of<B>
returning a std::tuple containing all base classes of B
?
Is there ev开发者_如何学Pythontl. a non-standard extension in g++ that can accomplish this ?
If this is not possible at all, does anyone know why? It sounds like a rather fundamental piece of information the compiler easily should have available?
Example:
#include <type_traits>
#include <tuple>
struct A {};
struct B : A {};
static_assert(std::is_base_of<A, B>::value, "A is base of B");
static_assert(! std::is_base_of<B, A>::value, "but B is not base of A");
// now I am looking for something like
// typedef base_classes_of<B>::type B_bases;
// static_assert(std::is_same<B_bases, std::tuple<A>>::value, "all bases of B are: A");
int main() {}
Similar facility bases
and direct_bases
were proposed in
N2965.
As for data members, since data members can be bit-fields, their type traits
have some subtleties.
On the other hand, base classes don't have such problems.
I think there is the demand on some compile-time query like bases
in some situations, as mentioned in Motivating examples of N2965.
However, unfortunately, current C++ just lacks it, and as far as I saw,
GCC and Clang-C++ seem not to provide similar facilities at the moment...
No, it's not possible in standard C++, but for your intended purpose you can just use individual asserts, one for each base class you need to be present (or wrap that with a typelist).
Cheers & hth.,
It is not possible to query a C++ program for base types of a given type - it is actually not possible to query a C++ program for anything.... You could however write a meta-predicate, which queries a known type against a type list (or parameter pack) of known types (or vice-versa) and generates an true or false type at compile type - it would just recursively apply std::is_base_of
meta predicate to all types in the parameter pack and accumulate the results. This is the only way I can think of. I could spin some code which does that but I doubt that is what you really want. The really question is: why do you need to do that, or better why do you need to that in C++?
精彩评论