重载运算符<<用于数组,无需类
Overloading operator<< for array without the need of a class
我有一个问题。在C 中,我可以超载operator<<
,以便我可以打印一个给定尺寸的数组,而无需课程吗?我设法打印了一个数组,但前提
是的,绝对可以做到。
继续定义该操作员的过载以采用您想要的任何东西。它不需要类型。
所以,类似的东西:
template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
for (const auto& el : arr)
os << el << ' ';
return os;
}
(实时演示(
但是,我警告不要对此过分;其他使用您的代码的程序员可能不会期望它,而且没有其他没有类型的非类型类型(考虑所有整数,char
类型,bool
和Pointers和Pointers已经"做某事"流式传输时(。
完整的演示代码,用于后续:
#include <iostream>
#include <cstddef>
template <typename T, std::size_t N>
std::ostream& operator<<(std::ostream& os, const T (&arr)[N])
{
for (const auto& el : arr)
os << el << ' ';
return os;
}
int main()
{
int array[] = {6,2,8,9,2};
std::cout << array << 'n';
}
// Output: 6 2 8 9 2
另一种做到这一点的方法是用std::copy
和std::ostream_iterator
#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstddef>
template <typename T, auto N>
auto& operator<<(std::ostream& os, T(&arr)[N])
{
std::copy(std::cbegin(arr), std::cend(arr), std::ostream_iterator<T>(os, " "));
return os;
}
int main()
{
int array[] = { 6, 2, 8, 9, 2};
std::cout << array << 'n';
}
// Output: 6 2 8 9 2
相关文章:
- 1d 智能指针不适用于语法 (*)++
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 用于访问容器<T>数据成员的正确 API
- 重载操作程序时出错>>用于类中的字符串 memebr
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- C++中的cin.ignore()函数不适用于整个流
- 没有用于初始化C++中的变量模板的匹配构造函数
- 呼叫运营商<<临时
- 用于C++中带有数组和指针的循环
- 为什么它不适用于Visual 2019的原因
- 使用在用于SFINAE的void_t中具有参数的方法
- 在createdialog创建的窗口中捕获用于编辑控件的OnMouseMove消息
- 过载输出<<用于类的运算符,以打印其中的元组
- 重载运算符<<用于模板类.即使使用好友关键字也无法获得私人会员
- 如何过载<<用于YAML::Emitter的运算符,以序列化包含另一个自定义类的向量的自定义类
- 重载运算符<<用于ostream语法
- 运算符<<(ostream&os,..)用于模板类
- 重载& lt; & lt;用于打印自定义异常的操作符
- Can运算符<<用于设计我们自己的输出显示方式