C++:模板类的嵌套类

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;.

  • 感谢您的回答.为什么`T`不能从函数参数推导出来?你能举一个例子,其中`T`有两种类型可以匹配一个特定的`f`调用吗?你的意思是,对于`A`的另一个特化,它可能是另一个`typedef int B;`而不是`struct B {};`?我不明白为什么在这种情况下`f`的调用应该是模棱两可的. (3认同)