![](/img/trans.png)
[英]Specialize a template to only take a typename of a class with template arguments
[英]specialize template<typename T, template<typename> class U>
我對嵌套模板及其模板專業化有疑問。 給定以下課程:
小模板 class
template<class U>
class T {
public:
T(){}
virtual ~T (){}
};
和某種嵌套模板
template<typename T, template<typename> class U>
class A {
public:
void foo()
{
std::cerr << "A generic foo";
}
};
還有一個小的 main.cpp
int main(int argc, const char *argv[])
{
A<int,T> *a = new A<int,T>;
a->foo();
//This wont work:
A<double,T*> *b = new A<double,T*>;
b->foo();
return 0;
}
如果 U 是指針,現在我需要一個專業化:
A<double,T*> *b = new A<double,T*>;
b->foo();
如何做到這一點? 我試過類似的東西:
template<typename T, template<typename> class U>
class A< T, U* >
{
public:
void foo()
{
std::cerr << "A specialized foo";
}
};
但它只是解決了
A.h:18:16: Error: Templateargument 2 is invalid
你要做的事情是不可能的,因為T*
沒有意義。 它既不是正確的類型,也不匹配需要額外參數的模板。 如果U
代表T*
,那么U<int>
會是什么? 您可能是說T<int>*
但這與您的聲明不匹配,因此無法將該類型插入A
。
既然你問了一個解決這個問題的方法,從我的頭頂開始,就像這樣。
接受A
的第三個模板參數,我將其稱為Expander
並將其默認設置為:
template <typename T> struct Expander {
typedef T type;
};
然后,在調用A
時你可以說
A<int,T> normal;
A<int,T,PtrExpander> pointer;
和
template <typename T> struct PtrExpander {
typedef T* type;
};
A
將是:
template<typename T, template<typename> class U, template <typename> class E = Expander> class A {
typedef typename E<U<Your_Args_to_U> >::type;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.