2012-08-29 39 views
0

林具有以下typedef的問題的模板,我似乎可以得到它的權利:的typedef用模板類型作爲參數

template <typename T> 
    struct myclass1 { 
    static const int member1 = T::GetSomeInt(); 
}; 

template <int I> 
struct myclass2 { 
    typedef myclass1< myclass2<I> > anotherclass; 
    static int GetSomeInt(); 
}; 

anotherclass MyObj1; // ERROR here not instantiating the class 

當我嘗試並初始化一個anotherclass對象,它給了我一個錯誤。

任何想法我做錯了什麼?我的typedef似乎有問題。

任何幫助表示讚賞,感謝 布賴恩

+0

你得到什麼錯誤? –

+0

你想要模板? – Grzegorz

+0

對不起,我編輯了我的答案並更好地解釋。 –

回答

3

您指的anotherclass直接。該名稱在該範圍內不存在。需要聲明的變量

myclass2<some_int>::anotherclass MyObj1; 

其中some_int是你要參數myclass2與任何整數值。

我想你還需要將myclass2<I>::GetSomeInt()標記爲constexpr,所以它可以在myclass1<T>::member1的初始化程序中使用。

有了這些調整,下面的代碼編譯就好:

#include <iostream> 

template<typename T> 
struct myclass1 { 
    static const int member1 = T::GetSomeInt(); 
}; 

template<int I> 
struct myclass2 { 
    typedef myclass1<myclass2<I>> anotherclass; 
    constexpr static int GetSomeInt() { return I; }; 
}; 

int main(int argc, char *argv[]) { 
    myclass2<3>::anotherclass obj; 
    std::cout << obj.member1 << std::endl; 
} 

注意,這需要constexpr C++ 11。如果你想要C++ 03,那麼我認爲你的myclass1<T>::member1是合法的。

0

您正在使用myclass1創建typedef並傳入模板化類作爲參數。因此您需要使用模板模板參數。這意味着myclass1的聲明應該改爲告訴編譯器,Ttemplate <typename T>本身就是一個模板類。

看看是否改變了下面的代碼

template <typename T> 
    struct myclass1 { 
    static const int member1 = T::GetSomeInt(); 
}; 

到這能解決問題:

template < template <typename BasicType> class T> 
    struct myclass1 { 
    static const int member1 = T::GetSomeInt(); 
}; 
+0

隨着我的答案中提到的調整,代碼編譯得很好。您不需要模板模板參數。 –

+0

感謝您的確認。我認爲它應該編譯原樣,除非指定了默認的模板參數。 – vvnraman

相關問題