在类中声明模板类,其类型与父类相同

时间:2015-01-06 10:56:54

标签: c++ templates namespaces ostream

为类范围内的类花费cout / shift operator<<

template <typename X, typename Y> class Foo {
public:
    template <typename A, typename B> class Bar {
        A a;
        B b;
    };

    Bar<X,Y> baba;
};

template <typename V, typename W>
std::ostream &operator<< (std::ostream& os, Foo<V,W>::template Bar<V,W> *b) {return os;}

这不编译。但如何正确地做到这一点?


错误:

error: expected template-id for type before ‘*’ token
  std::ostream &operator<<(std::ostream &os, Foo<V, W>::template Bar<V, W> *b)

1 个答案:

答案 0 :(得分:2)

应该是:

template <typename V, typename W>
std::ostream &operator<< (std::ostream& os, typename Foo<V,W>::template Bar<V,W> &b) {return os;}

但更改课程可能更简单:

template <typename X, typename Y> class Foo {
public:
    class Bar {
        X a;
        Y b;
    };

    Bar baba;
};

template <typename V, typename W>
std::ostream &operator<< (std::ostream& os, const typename Foo<V,W>::Bar& b) {return os;}

真正的解决方案(避免类型推导问题)是将自由函数放在类中:

template <typename X, typename Y> class Foo {
public:
    class Bar {
        X a;
        Y b;

        friend
        std::ostream &operator<< (std::ostream& os, const Bar &b) {return os;}
    };

    Bar baba;
};