c++ - 在与父类具有相同类型的类中声明模板类

标签 c++ templates namespaces ostream

花式计算/移位 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)

最佳答案

应该是:

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

关于c++ - 在与父类具有相同类型的类中声明模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27797176/

相关文章:

c++ - 默认情况下,静态变量是否在 C++17 的模板中内联?

c# - 为什么我被迫使用完整的命名空间?

php - Laravel 4 命名空间没有\

c++ - 使用方法返回值作为参数c++

c++ - 访问未初始化的值会导致性能下降吗?

c++ - Windows 编辑启动应用程序/C++

c++ - 实现 OpenSceneGraph 时在 Qt 中获取引用问题

c++ - 如何专门化容器的功能模板?

php - 解析电子邮件或 html 模板的最佳方法是什么?

c++ - 如何防止 C++ 模板的特化?