相关疑难解决方法(0)

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;
}
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 < …
Run Code Online (Sandbox Code Playgroud)

c++ gcc templates nested-class gcc4

14
推荐指数
1
解决办法
1万
查看次数

在模板中输出嵌套类

我正在尝试重载ostream运算符以允许输出模板内的嵌套类.但是,编译器无法将实际函数调用绑定到我的重载.

template <class T>
struct foo
{
    struct bar { };
};

template <class T>
std::ostream& operator << (std::ostream& os, 
    const typename foo<T>::bar& b)
{
    return os;
}

int main()
{
    foo<int>::bar b;
    std::cout << b << std::endl; // fails to compile
}
Run Code Online (Sandbox Code Playgroud)

如果我将重载定义为内联friend函数,这将编译:

template <class T>
struct foo
{
    struct bar 
    { 
        friend std::ostream& operator << (std::ostream& os, const bar& b)
        {
            return os;
        }
    };
};
Run Code Online (Sandbox Code Playgroud)

但我宁愿在课外定义重载.这可能吗?

c++ templates iostream

5
推荐指数
1
解决办法
676
查看次数

标签 统计

c++ ×2

templates ×2

gcc ×1

gcc4 ×1

iostream ×1

nested-class ×1