检查嵌套mixin

时间:2016-03-01 01:08:35

标签: c++ c++11

我有一组mixin,每个都有一个定义的类型特征。我想检查每个mixin的每个特征的布尔值的值。例如,如果我有Mixin1<Mixin2<T> >Mixin1<T>is_nice == trueMixin2<T>is_nice == false,那么嵌套混合的特征应评估为&#34假#34;

#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;
}

这是不是很奇怪&#34;还是一个合理的事情呢?我没有看到大量关于在线使用mixins的问题 - 这种添加属性的模式是不是经常在实践中使用?

1 个答案:

答案 0 :(得分: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;
};