Consider the following code:
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 );
是无效的。你能否参考一些标准中说明这样的调用应该是无效的点?你能否提供一个这样的调用会导致歧义的例子吗?
typedef int B;
而不是struct B {};
吗?我看不出在这种情况下为什么调用 f 会产生歧义。 - Vahagn