2008-11-24 70 views
3

考慮以下使用的模板,模板參數...如何申報/定義模板與模板參數的一類,而無需使用額外的模板參數

#include <iostream> 

template <typename X> 
class A 
{ 
    X _t; 
public: 
    A(X t) 
     :_t(t) 
    { 
    } 
    X GetValue() 
    { 
     return _t; 
    } 
}; 

template <typename T, template <typename T> class C > 
class B 
{ 
    C<T> _c; 
public: 
    B(T t) 
     :_c(t) 
    { 
    } 
    T GetValue() 
    { 
     return _c.GetValue(); 
    } 
}; 

using namespace std; 

int main() 
{ 
    B<int, A> b(10); 
    cout<<b.GetValue(); 
    return 0; 
} 

有沒有一種方法,通過該模板參數T可以去掉?例如,是否有辦法做以下工作?

//Does not compile 
template <template <typename T> class C > 
class B 
{ 
    C _c; 
public: 
    B(T t) 
     :_c(t) 
    { 
    } 
    T GetValue() 
    { 
     return _c.GetValue(); 
    } 
}; 

int main() 
{ 
    B< A<int> > b(10); 
    cout<<b.GetValue(); 
    return 0; 
} 

回答

8

我假設你在代碼中的X和A之後。

通常的模式是有

template<typename C> 
struct B 
{ 
    C c; 
}; 

,然後在類資格替代:

template<typename X> 
class A 
{ 
    typedef X type_name; 
    X t; 
}; 

然後你就可以訪問使用C::type_name模板參數。

+0

感謝您的回答,儘管我最終自己發現了這個。我正在編輯問題併發布我的工作,但顯然我來到正確的地方問這個問題! – 2008-11-24 14:05:07

+0

請注意,陽光的答案比我的好,因爲他已經明白你想要什麼。無需像我向你展示的那樣重新綁定。只有在您使用A 時才需要此功能,但偶爾會有需要或A 。或者如果用戶的視圖是A ,但是您使用A 。 – 2008-11-24 14:14:33

1

什麼是錯的:

template <typename C > 
struct B 
{ 
    C c; 
}; 

int main() 
{ 
    B< A<int> > b; 
    return 0; 
} 
+0

我的不好,問題沒有完全說明。現在它是。 – 2008-11-24 14:06:41

4

這是不可能的。請注意,這是一個常見的誤解:A<int>不再是類模板!因此,這將不適合的模板,模板參數,但必須使用一個類型參數被接受:

template<typename C> 
struct B { 
    C c; 
}; 

B< A<int> > b; 

你使用一個單獨的參數的方式是好的。

如果你想接受A<int>,但想重新將其綁定到另一個參數,你可以使用這個模式,還使用標準分配器:

template<typename T> 
struct A { 
    template<typename U> 
    struct rebind { 
     typedef A<U> type; 
    }; 
}; 

template<typename C> 
struct B { 
    typename C::template rebind<float>::type c; 
}; 

B< A<int> > b; 

現在,B< A<int> >::cA<float>類型。在C::之前的typename告訴編譯器::type最後是一個類型而不是靜態的非類型成員。 C::之後的template告訴編譯器rebind<float>是一個模板實例化,而不是比較。

+0

好酷!很好的答案,但不幸的是,只能有一個答案,我認爲@sunlight早些時候向你發佈了他的解決方案。我已經提出了你的答案。 – 2008-11-24 14:14:28

1

您可以嵌套參數。也就是說,參數的值本身可以被參數化。

template <typename X> 
struct A 
{ 
    X t; 
}; 

template <typename C> 
struct B 
{ 
    C c; 
}; 

int main() 
{ 
    B< A<int> > b; 
    return 0; 
} 

在這個例子中,在bmain()聲明創建的使用int作爲參數A一個特例,然後它創建使用A<int>作爲參數的B專業化。因此,B,C的專業化爲A<int>

相關問題