如何检查父类有多少个子类

时间:2019-04-03 06:47:24

标签: c++

就像我可以简单地计算出子类在运行时有多少个父类,只需计算在该子类的构造函数之前运行的构造函数的数量即可,但是我怎么知道一个父类有多少个子类运行时间。

1 个答案:

答案 0 :(得分:0)

好的,我找到了答案,继承代码现在必须看起来像这样:

struct Parent3 { };
struct Parent2 : public InheritAndCount<Parent3> { };
struct Parent1 : public InheritAndCount<Parent2> { };

struct OtherParent { };
struct Child : public InheritAndCount<OtherParent, Parent1> { };

int main() 
{
    std::cout << "Child=" << Child::numberOfParents << ", Parent1=" << Parent1::numberOfParents << std::endl;
    return 0;
}

这将导致

  

孩子= 4,父母= 1

符合预期。现在是模板!

// First, this is a nice trick to find out if a class has a member
template<typename...>
struct MakeVoid { typedef void type; };

template<typename... Args>
using VoidType = typename MakeVoid<Args...>::type;

template<typename T, typename Nested = VoidType<>>
class TypeHasNumberOfParent : public std::false_type { };

template<typename T>
class TypeHasNumberOfParent<T, VoidType<decltype(T::numberOfParents)>> : public std::true_type { };

// Now we need to count the parents using SFINAE to only count derived classes - the classes that have
// the 'numberOfParents' field
template<class T>
static constexpr
typename std::enable_if<TypeHasNumberOfParent<T>::value, size_t>::type
CountParents()
{
    return T::numberOfParents + 1;
}

template<class T>
static constexpr
typename std::enable_if<!TypeHasNumberOfParent<T>::value, size_t>::type
CountParents()
{
    return 1;
}

// Recursivly count the tuple...
template<class TupleType, size_t index>
static constexpr
typename std::enable_if<index == 0, size_t>::type
CountImpl() {
    using Parent = typename std::remove_reference<decltype(std::get<0>(TupleType()))>::type;
    return CountParents<Parent>();
}

template<class TupleType, size_t index>
static constexpr
typename std::enable_if<index != 0, size_t>::type
CountImpl() {
    using Parent = typename std::remove_reference<decltype(std::get<index>(TupleType()))>::type;
    return CountParents<Parent>() + CountImpl<TupleType, index - 1>();
}

template<class TupleType>
static constexpr
size_t Count() {
    return CountImpl<TupleType, std::tuple_size<TupleType>::value - 1>();
}


// This is the inheritance mechanism you'll have to use to make it all work
template<class... Parents>
struct InheritAndCount : public Parents...
{
    using ParentsTuple = std::tuple<Parents...>;
    static constexpr const size_t numberOfParents = Count<ParentsTuple>();

};

在那里,你有:)