在C++ 03中,在某些上下文中不會發生模板參數推導。例如:模板別名如何影響模板參數推演?
template <typename T> struct B {};
template <typename T>
struct A
{
typedef B<T> type;
};
template <typename T>
void f(typename A<T>::type);
int main()
{
B<int> b;
f(b); // ERROR: no match
}
這裏,int
不推導出T
,因爲嵌套類型如A<T>::type
是非推導出上下文。
如果我寫的函數是這樣的:
template <typename T> struct B {};
template <typename T>
void f(B<T>);
int main()
{
B<int> b;
f(b);
}
一切都很好,因爲B<T>
是一個推斷上下文。
但是,在C++ 11中,可以使用模板別名以類似於第二個示例的語法來僞裝嵌套類型。例如:
template <typename T> struct B {};
template <typename T>
struct A
{
typedef B<T> type;
};
template <typename T>
using C = typename A<T>::type;
template <typename T>
void f(C<T>);
int main()
{
B<int> b;
f(b);
}
在這種情況下,模板參數推導工作嗎?換句話說,模板別名是推斷的上下文還是非推斷的上下文?或者他們是否繼承了他們別名的推導/未推導的狀態?
別名只是別名。這就像寫作'template void f(typename A :: type);',這是不可扣除的。 –
2012-01-08 03:43:19
可能重複的[C++,模板參數不能被推斷](http://stackoverflow.com/questions/6060824/c-template-argument-can-not-be-deduced) – Nawaz 2012-01-08 03:43:46
我認爲Kerrek SB是正確的對這個。如果提供了一個報價,我不需要去搜索一個;-) – 2012-01-08 03:45:57