我想實現operator <<
,它將打印模板類的內部類的內容,即X<T>::Y
。可以添加任何需要的friend
聲明。怎麼做?運算符<<用於模板類的內部類
這裏是什麼,我想在編譯C++ 11一個完整的例子:
#include <iostream>
template <typename T>
class X {
public:
X(T d): y(d) {}
private:
class Y {
public:
Y(T d): data(d) {}
private:
T data;
template <typename U>
friend std::ostream &operator <<(std::ostream &os, const typename X<U>::Y &y);
};
Y y;
template <typename U>
friend std::ostream &operator <<(std::ostream &os, const X<U> &x);
};
// This operator is not detected by the operator below
template <typename U>
std::ostream &operator <<(std::ostream &os, const typename X<U>::Y &y) {
os << "Y(" << y.data << ")";
return os;
}
template <typename U>
std::ostream &operator <<(std::ostream &os, const X<U> &x) {
os << "X " << x.y;
return os;
}
int main() {
std::cout << X<int>(1);
return 0;
}
編譯器的錯誤,我得到的是:
error: no match for 'operator<<' (operand types are 'std::basic_ostream<char>' and 'const X<int>::Y')
os << "X " << x.y;
^
的'U'在'類型名稱X :: Y'是在非推斷上下文。 – 2014-09-19 09:17:33