2016-02-12 39 views
1

我希望能夠改變mixin最內層類型的類型。草圖如下所示:構造一個改變mixin基類的類型

struct PointTypeA { 
    double x,y; 
}; 

struct PointTypeB { 
    double x,y,z; 
}; 

template<class Base> 
class MyMixin1 : public Base { 
public: 
    double someProperty; 
}; 

template<class Base> 
class MyMixin2 : public Base { 
public: 
    double someProperty; 
}; 

// how do we automatically construct MyMixin2<MyMixin1<TNewInside> > from MyMixin2<MyMixin1<PointTypeA> > 
// template <typename T, typename TNewInside> 
// ChangedType ChangeInsideType(T object) { 
//  return ChangedType(object); 
// } 

int main() { 
    typedef MyMixin2<MyMixin1<PointTypeA> > Mixed12A; 
    Mixed12A mixed12A; 

    //MyMixin2<MyMixin1<PointTypeB> > mixed12B = ChangeInsideType<Mixed12AType, PointTypeB>(mixed12A); 
    return 0; 
} 

是這樣的可能嗎?

template <class ToReplace, class With> 
struct replace_inner { 
    using type = With; 
}; 

template <template <class> class Outer, class Inner, class With> 
struct replace_inner<Outer<Inner>, With> { 
    using type = Outer<typename replace_inner<Inner, With>::type>; 
}; 

template <class ToReplace, class With> 
using replace_inner_t = typename replace_inner<ToReplace,With>::type; 

我們使用它像這樣:

using replaced = replace_inner_t<MyMixin1<MyMixin2<PointTypeA>>, PointTypeB>; 
static_assert(
    std::is_same<replaced, MyMixin1<MyMixin2<PointTypeB>>>::value, "wat" 
); 

然後你只需要編寫點類型和混合類型之間的轉換構造

+0

你可以使用C++ 11嗎? – TartanLlama

+0

@TartanLlama當​​然。 –

回答

1

更換內模板參數可以用這個來完成具有不同的模板參數。

+0

令人驚歎的,謝謝。現在,我只需要取消我週末的計劃來研究發生了什麼:) –

+0

@DavidDoria實際上,它會向外遞減外部類型,直到用完爲止,然後用指定的內部類型替換內部類型。 – TartanLlama

+1

我想我正在接近。對於3個代碼塊:1)這是遞歸的基本情況,它在內部類型到達非模板類時切換內部類型。 2)這是replace_inner的部分專用版本,其中第一個模板參數是模板模板參數(這是我們的mixins將顯示爲Outer的地方)。在這個「使用類型」裏面,我們有遞歸,在Inner上調用replace_inner。 3)便利的typedef。 我的困惑是專業化 - 當原始的replace_inner只有2個參數時,它怎麼會有3個參數? –