2016-03-01 66 views
0

我有一個mixin集合,每個混合都有一個類型trait定義。我想檢查每個這些mixin的每個特徵的布爾值AND。例如,如果我有一個Mixin1<Mixin2<T> >Mixin1<T>具有is_nice == trueMixin2<T>具有is_nice == false,則嵌套mixin的特徵應評估爲「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; 
} 

這是「奇怪」還是合理的事情?我沒有看到有關在線使用mixins的許多問題 - 這種模式是否添加了實踐中不經常使用的屬性?

+2

也許你想'靜態常量布爾值= is_nice <外> ::值&& is_nice_all ::值;'。請注意,在您的示例中,儘管您沒有爲「Mixin1」和「Mixin2」定義模板特化,但它會輸出0。我不確定如何檢查'is_nice'是否爲'Outer'的特定基類,即您有模板專門化的'Mixin1_Fields'和'Mixin2_Fields'。 – user2093113

+0

@ user2093113哇,我非常專注於困難的部分,所以我剔除了明顯的部分。我已經通過工作示例更新了問題。但是,如果這是「奇怪的」或合理的事情,我仍然很好奇。 –

+0

從nicer_tag繼承並只檢查它的繼承是不是更簡單? – Jarod42

回答

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; 
}; 
+0

你是什麼意思,這個特質不適用於Derived?有沒有一種不同的方式來定義特徵,所以它會適用? –

+0

我沒有遵循'FieldsType'技巧來傳播特質。所以你的代碼工作。 – Jarod42