2013-12-16 24 views
1

我想將一些參數傳遞給一個好奇的重複模板模式。然後,我會喜歡這個基類創建其他對象並將這兩種類型傳遞給子類。這將允許我推廣基類來在調用子類之前執行一些通用邏輯。每個子類應該能夠成爲一個一級層次結構的專門實例。如何使用和專門化'好奇的重複模板模式'

回答

0

這裏是如何做到這一點:在GCC 4.8.1

struct ParamOne { 
    double val {0.0}; 
}; 

struct ParamTwo { 
    int val {0}; 
}; 

template<typename P, typename Data, typename Other> 
class Baseclass 
{ 
public: 
    using subclass_type = P; 
    using data_type = Data; 
    using other_type = Other; 

    bool Method(const Data &data); 
}; 

template<typename P, typename Data, typename Other> using pdata_type = typename P::data_type; 
template<typename P, typename Data, typename Other> using pother_type = typename P::other_type; 

template<typename P, typename Data, typename Other> 
bool Baseclass<P, Data, Other>::Method(const Data &data) 
{ 
    P& Subclass = static_cast<P&>(*this); 
    pother_type<P, Data, Other> other; 
    other.val = 11; 

    return Subclass.SubclassMethod(data, other); 
} 

template<typename Data, typename Other> 
class Subclass : public Baseclass<Subclass<Data, Other>, Data, Other> 
{ 
public: 
    using data_type = Data; 
    using other_type = Other; 

    bool SubclassMethod(const Data &data, Other &other); 
}; 

template<typename Data, typename Other> 
bool Subclass<Data, Other>::SubclassMethod(const Data &data, Other &other) 
{ 
    return true; 
} 

template<> 
bool Subclass<ParamOne, ParamTwo>::SubclassMethod(const ParamOne &data, ParamTwo &other) 
{ 
    return true; 
} 

int main(int argc, char **argv) 
{ 
    ParamOne one; 
    one.val = 5.0; 

    Subclass<ParamOne, ParamTwo> test; 

    test.Method(one); 
    return 0; 
} 
+0

注意,如果我添加到BaseClass的和子非靜態變量並打印出與子類{}初始化的建設值 :: SubclassMethod然後添加到BaseClass的值是正確的,但Subclass中的值無法正常工作。 –

+0

我已經將它作爲錯誤提交給gcc作爲錯誤編號:60201. –

+0

自創建測試對象以來的更正的代碼應該是子類 test; –