检查嵌套混合中每个类的类型特征

Check a type trait of every class in a nested mixin

本文关键字:类型 特征 嵌套 混合 检查      更新时间:2023-10-16

我有一个混合的集合,每个混合体都有一个类型特征。我想检查布尔值的值以及每个混合的这种特征的值。例如,如果我有一个Mixin1<Mixin2<T> >并且Mixin1<T>is_nice == trueMixin2<T>is_nice == false,那么嵌套混合蛋白的特征应该计算为"假"。

#include <iostream>
// A type trait to determine if a type is nice
template <typename T>
struct is_nice
{
  static const bool value = false;
};
// Base case
template <class T>
struct is_nice_all {
    static_assert(is_nice<typename T::FieldsType>::value, "Not nice!");
    static const bool value = is_nice<typename T::FieldsType>::value;
};
template <template <class> class Outer, class Inner>
struct is_nice_all<Outer<Inner> > {
    // AND the result of the niceness of the current mixin and the next mixin, recursively
    static const bool value = is_nice< typename Outer<Inner>::FieldsType >::value && is_nice_all<Inner>::value;
};
class BaseClass
{
public:
    using FieldsType = BaseClass;
};
template <>
struct is_nice<BaseClass>
{
  static const bool value = true;
};
class Mixin1_Fields
{
public:
    int property1;
};
template<class MixinBase>
class Mixin1 : public MixinBase, public Mixin1_Fields
{
public:
    using FieldsType = Mixin1_Fields;
};
template <>
struct is_nice<Mixin1_Fields>
{
  static const bool value = true;
};
class Mixin2_Fields
{
public:
    int property2;
};
template<class MixinBase>
class Mixin2 : public MixinBase, public Mixin2_Fields
{
public:
    using FieldsType = Mixin2_Fields;
};
template <>
struct is_nice<Mixin2_Fields>
{
  static const bool value = true;
};
class Mixin3_Fields
{
public:
    int property3;
};
template<class MixinBase>
class Mixin3 : public MixinBase, public Mixin3_Fields
{
public:
    using FieldsType = Mixin3_Fields;
};
template <>
struct is_nice<Mixin3_Fields>
{
  static const bool value = false;
};
int main()
{
    std::cout << is_nice_all<Mixin1<Mixin2<BaseClass> > >::value << std::endl;
    std::cout << is_nice_all<Mixin1<Mixin3<BaseClass> > >::value << std::endl;
    return 0;
}

这是"奇怪"还是合理的做法?我没有看到很多关于在线使用这样的混合 - 这种添加属性的模式在实践中不经常使用吗?

您不想对自身进行递归,而只想在Inner上执行递归,并对当前类型使用常规值

template <template <class> class Outer, class Inner>
struct is_nice_all<Outer<Inner> > {
    // AND the result of the niceness of the current mixin and the next mixin, recursively
    static const bool value = is_nice<typename Outer<Inner>::FieldsType>::value
                              && is_nice_all<Inner>::value;
};