operator << C++中模板类中成员类型的重载

Kem*_*mal 3 c++ templates operator-overloading type-members

在下面的代码中,我有一个带有成员类型(struct Element)的模板类.我想为该成员类型重载operator << .但是,代码不会编译.

如果有人能指出我哪里出错了,我将不胜感激?

include <iostream>
using namespace std;

// fwd decl
template<class T> class CC;

// operator<< overload template for member type CC<T>::Element
template<class T>
ostream& operator<<(ostream& os, const typename CC<T>::Element& elm) {
    return os << elm.val1 << "/" << elm.val2;
}

template<class T>
class CC
{
public:
    struct Element {    // type member
        int val1;
        int val2;
    };

    template<typename U>
    friend ostream& operator<<(ostream& os, const typename CC<U>::Element& elm);
};

int main() {
    CC<int>::Element elm{0,0};
    cout << elm << endl;     // does not compile due to this!
}
Run Code Online (Sandbox Code Playgroud)

Die*_*ühl 9

无法从嵌套实体推断出模板参数(简短说明:不同模板实例化的类型可能是seame).那就是声明

template<typename U>
ostream& operator<<(ostream& os, const typename CC<U>::Element& elm);
Run Code Online (Sandbox Code Playgroud)

是否friend从未考虑过是否因为类型U无法推断.您可以通过使friend运算符成为非模板来解决问题:

// ...
friend ostream& operator<<(ostream& os, const Element& elm) { ... }
// or
friend ostream& operator<<(ostream& os, const CC<T>::Element& elm) { ... }
// ...
Run Code Online (Sandbox Code Playgroud)

但是,该功能需要在其声明中实施.