C ++:模板类的嵌套类 [英] C++: nested class of a template class
问题描述
请考虑以下代码:
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
?
So here gcc-4.1.2 requires the template argument of f
to be explicitly specified. Is this meet the standard? Does the newer versions of GCC have this issue fixed? How can I avoid explicitly specifying int
while calling f
?
更新:
以下是解决方法。
Update: Here is a workaround.
#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;
}
$ b < f(x); 无效。你可以参考标准中的一些点,说这样的调用应该是无效的吗?
However, I still can't see why call f( x );
is invalid. Can you refer to some point in the standard which says such call should be invalid? Can you bring an example where such call is ambiguous?
推荐答案
typename A<T>::B
这里, T
一个非削减的上下文,这意味着 T
不能从函数参数中推导出。
Here, T
is in a nondeduced context, which means that T
cannot be deduced from the function argument.
问题是在一般情况下,可能有无数个可能匹配的类型 T
。例如,如果不是 struct B {};
你有 typedef int B;
。
The problem is that in the general case, there is a potentially infinite number of possible types T
that could match. Consider, for example, if instead of struct B { };
you had typedef int B;
.
这篇关于C ++:模板类的嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!