考慮下面的代碼:C++:嵌套類模板類
template < typename T >
struct A
{
struct B { };
};
template < typename T >
void f(typename A<T>::B) { }
int main()
{
A<int>::B x;
f(x); // fails for gcc-4.1.2
f<int>(x); // passes
return 0;
}
所以在這裏GCC-4.1.2需要f
模板參數被明確指定。這是否符合標準?新版本的GCC是否解決了這個問題?我如何避免在撥打f
時明確指定int
?
更新: 這是一種解決方法。
#include <boost/static_assert.hpp>
#include <boost/type_traits/is_same.hpp>
template < typename T >
struct A
{
typedef T argument;
struct B { typedef A outer; };
};
template < typename T >
void f(typename A<T>::B) { }
template < typename Nested >
void g(Nested)
{
typedef typename Nested::outer::argument TT;
BOOST_STATIC_ASSERT((boost::is_same< typename A<TT>::B, Nested >::value));
}
struct NN
{
typedef NN outer;
typedef NN argument;
};
int main()
{
A<int>::B x;
NN y;
g(x); // Passes
g(y); // Fails as it should, note that this will pass if we remove the type check
f(x); // Fails as before
return 0;
}
不過,我仍然不明白爲什麼叫f(x);
是無效的。你能否在標準中提到這種呼叫應該是無效的一點?你能舉出一個這樣的電話不明確的例子嗎?
感謝您的回答。爲什麼'T'不能從函數參數中推導出來?你能舉一個例子來說明'T'有兩種類型,它們與'f'的特定調用相匹配嗎?你的意思是,對於'A'的另一個專門化,它可能是另一個'typedef int B;'而不是'struct B {};'?我看不出爲什麼在這種情況下'f'的調用應該是不明確的。 – Vahagn 2010-11-04 07:58:01