2012-08-23 275 views
2

鑑於下面的代碼模板專業化

template<typename T> 
struct A{ 
    struct In{}; 

}; 

template<typename T> 
struct Desc{ 
}; 


template<typename X> 
struct Desc<typename A<X>::In> { 
}; 



int main(){ 
    Desc<A<int>::In> a; 
} 

編譯器拒絕說明專業化與

error: template parameters not used in partial specialization: 
error:   ‘X’ 

相同的,如果該結構是由

template<> 
template<typename X> 
struct Desc<typename A<X>::In> { 
}; 
定義

定義

template<typename X> 
template<> 
struct Desc<typename A<X>::In> { 
}; 

給出了錯誤

desc.cpp:14:10: error: invalid explicit specialization before ‘>’ token 
desc.cpp:14:10: error: enclosing class templates are not explicitly specialized 
desc.cpp:15:8: error: template parameters not used in partial specialization: 
desc.cpp:15:8: error:   ‘X’ 

這是「非推論語境」這裏的情況?

Template parameters not used in partial specialization

這將是有意義的,因爲沒有保證內部類實際上是一類(我們只知道它是類型名,它可能是一個typedef)。 那麼是否有方法來指定它是一個真正的類?

+1

恐怕是這樣。你不能專門爲'A '嗎?在專業領域內,當然可以在任何地方使用'A :: In'。 – Gorpik

回答

2

有那麼可以指定它的方式是一個真正的類

沒有,有沒有辦法來指定,如果使用這種類型的模板偏特。

只有兩種方法。專門Desc混凝土A,所以,

template<> 
struct Desc<typename A<type>::In> { }; 

或使用類似

template<typename T, typename = void> 
struct Desc{ 
}; 


template<typename X> 
struct Desc<X, typename A<X>::In> { 
}; 

或課程專門爲A<X>不是類型A<X>::In

+0

我懷疑他的'A :: In'是'void'。 –