重载模板类和嵌套类的输出运算符
Overloading the output operator for a template class and a nested class
有一个模板类,其中嵌套了一个子类。如何正确地将输出运算符重载到外部类的流中,该类是一个模板,其中流的输出运算符是从嵌套类调用的?在我的情况下,会出现编译错误:
"struct-std::enable_if<"中没有名为"type"的类型;false,void>'
不匹配'operator<lt;'(操作数类型为"std::basic_stream"answers"Nesting::Nested"(
我在下面给出我的代码。
#include <iostream>
#include <string>
using namespace std;
template<typename T>
class Nesting {
public:
class Nested {
public:
T data;
Nested(const T & data): data(data) {;}
template<typename U>
friend ostream & operator<<(ostream & out, const typename Nesting<U>::Nested & nested);
};
T data;
Nested * pNested;
Nesting(const T & data)
: data(data)
, pNested(new Nested(222)) {;}
template<typename U>
friend ostream & operator<<(ostream & out, const Nesting<U> & nesting);
};
template<typename T>
ostream & operator<<(ostream & out, const typename Nesting<T>::Nested & nested) {
out << "Nested: " << nested.data;
return out;
}
template<typename T>
ostream & operator<<(ostream & out, const Nesting<T> & nesting) {
out << "Nesting: " << nesting.data << ", " << *nesting.pNested << endl;
return out;
}
int main() {
Nesting<int> n(111);
cout << n << endl;
return 0;
}
我认为最简单的方法是提供与声明内联的定义。
#include <iostream>
#include <memory>
#include <string>
using std::cout;
using std::make_unique;
using std::ostream;
using std::unique_ptr;
template<typename T>
class Nesting {
public:
class Nested {
public:
T data;
Nested(T const& data_): data{data_} {}
friend auto operator<<(ostream& out, Nested const& nested) -> ostream& {
return out << "Nested: " << nested.data;
}
};
T data;
unique_ptr<Nested> pNested;
Nesting(T const& data_)
: data{data_}
, pNested{make_unique<Nested>(222)} {}
friend auto operator<<(ostream& out, Nesting const& nesting) -> ostream& {
return out << "Nesting: " << nesting.data << ", " << *nesting.pNested;
}
};
int main() {
Nesting<int> n(111);
cout << n << "n";
}
您可以添加一个包装来删除依赖类型推导。类似于:
template<typename T>
struct NestingNested
{
const Nesting<T>::Nested & nested;
template<typename U>
friend std::ostream & operator<<(std::ostream & out, const NestingNested<U> & nested);
};
template<typename T>
std::ostream & operator<<(std::ostream & out, const NestingNested<T> & nested) {
out << "Nested: " << nested.nested.data;
return out;
}
template<typename T>
std::ostream & operator<<(std::ostream & out, const Nesting<T> & nesting) {
out << "Nesting: " << nesting.data << ", " << NestingNested<T>{ *nesting.pNested } << std::endl;
return out;
}
编译器资源管理器
相关文章:
- 尝试重载输出运算符时,我无法遍历对象向量
- 如何为流输出运算符提供重载<<模板'using'类型别名?
- 在C++中重载输入/输出运算符
- 如何处理自定义输出运算符中的 iomanips?
- 基于对函数的参数调用流输出运算符的能力重载函数
- C++将 toString 替换为重载的输出运算符
- 尝试过载输出运算符时出错
- 重载输出运算符给出十六进制数字而不是字符串
- 重载输入/输出运算符,为什么它以这种方式工作而不是以另一种方式工作
- Qt 使用迭代器重载了 qtextstream 输出运算符
- 抽象类和派生类的输出运算符 (<<)
- 重载输出运算符和后置增量运算符时"运算符<<"错误不匹配
- 如何在输出运算符中测试std::showbase或std::noshowbase
- 队列类C++的输出运算符重载
- 变量类型和变量模板的转换和输出运算符
- 重载输出运算符<<以使用 STL 列表迭代器
- C++抽象类的输出运算符
- 重载基类及其派生类(C++)的输出运算符
- 重载输出运算符时出现错误
- 为什么我的输出运算符 <<() 函数定义会导致无法解析的外部符号错误?