Vah*_*agn 14 c++ gcc templates nested-class gcc4
请考虑以下代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
所以这里gcc-4.1.2要求f
明确指定模板参数.这符合标准吗?较新版本的GCC是否修复了此问题?如何避免int
在调用时明确指定f
?
更新: 这是一个解决方法.
#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;
}
Run Code Online (Sandbox Code Playgroud)
但是,我还是看不出为什么通话f( x );
无效.你能否参考标准中的某些观点,说这种呼叫应该是无效的?你能举出这样一个模糊不清的例子吗?
Jam*_*lis 10
typename A<T>::B
Run Code Online (Sandbox Code Playgroud)
这里,T
是在非弱的上下文中,这意味着T
不能从函数参数推断出来.
问题是在一般情况下,可能有无数种T
可能匹配的类型.例如,考虑一下,而不是struct B { };
你typedef int B;
.