如何将 std::cout 与我的(模板化)类一起使用
How to use std::cout with my (templated) class?
我想重载<<
运算符,将类实例打印到控制台,如下所示:
std::cout << instance << std::endl;
我在这里找到了一个解决方案:https://msdn.microsoft.com/en-us/library/1z2f6c2k.aspx
但我不能使用它,因为我的类是模板化的:
template<typename T>
myClass {
//code...
};
编辑:如果我尝试在类体内定义它,我会收到一个错误:it must take only one argument
当然,您可以使用该示例,只需针对您的模板对其进行调整即可。
而不是
ostream& operator<<(ostream& os, const Date& dt)
你需要
template<class T>
ostream& operator<<(ostream& os, const myClass<T>& dt)
你可以试试这个(适应你的代码):
std::ostream& operator<<(std::ostream& os, const T& obj)
{
// write obj to stream
return os;
}
相关文章:
- 将fold表达式与std::一起用于两个元组
- 将 std::allocate_shared 与多态资源分配器一起使用
- 将 std::set 与基于键的比较器一起使用
- 如何将AERT_Allocate与 std:vector 一起使用
- 将用户定义的类型与 std::vector 和 std::sort 一起使用
- 将图形属性与 std::unique_ptr 捆绑在一起
- 将 std::map::emplace 与返回 shared_ptr 的函数一起使用是否正确?
- 将新放置与 std::函数一起使用不起作用
- 不能将C++的"std::filesystem"库与介子构建一起使用
- 将 std::function 与模板一起使用
- 是否可以将 std::basic_ifstream 和 std::basic_ofstream 与自定义缓冲区一起使用?
- 当返回语句时,逗号运算符、大括号初始化列表和 std::unique_ptr 组合在一起
- 如何将 std::find() 与 2d std: 数组一起使用?
- boost::interprocess::file_lock 与 std::ostream 一起使用时的错误行为
- std::remove() 按预期处理文字,但不能与取消引用的迭代器一起工作
- 将 std::transform 与 std::back_inserter 一起使用是否有效?
- 为什么使用与父级声明的 std::function 在与子级一起使用时会显示错误?
- 是否已经有一个 constexpr std::bit_cast 与 g++ 一起使用
- 将 std::variant 与 gmock 1.8 对象一起使用时编译错误
- 我不能将 'fill' std::vector 构造函数与 unique_ptrs 一起使用