c++11的特定过载<<操作人员
c++11 specefic overload of << operator
对于一个赋值,我必须按照一些明确的说明编写一个矩阵类。指令之一是使<lt;运算符,这样我们就可以以这种精确的方式读取矩阵m:的值
m << 1,2,3,4,5,6;
我试着研究具有可变参数的函数,但后来发现我不能用可变数量的参数重载运算符。
我试着在std::initializer_list中查找,使用了一些来自cpp引用的引用代码
std::vector<float> mat;
Mat<M,N>& operator<<(std::initializer_list<float> l)
{
this->mat.insert(this->mat.begin(),l.begin(),l.end());
return *this;
}
所以我的问题是,我可以使用什么类/类型的参数来实现这一点,我想到的选项不起作用,或者我没有以正确的方式使用它们。
非常感谢。
编辑:在@bames53的精彩回答之后,我尝试融入其中,效果非常好!
<<
的优先级高于,
,因此表达式m << 1,2,3,4,5,6
的作用是:
((((((m << 1), 2), 3), 4), 5), 6)
换句话说,您需要m << 1
返回一个对象,该对象表示在1
中进行读取的操作,并且准备在2
中进行读取。这类事情通常是用一种名为"表达式模板"的东西来完成的,尽管在您的情况下,您并不真正需要模板。
您的用法有一个不同之处,即您确实需要在进行过程中修改对象,而通常的表达式模板操作缓慢,等待对象转换为最终结果类型后再进行实际操作。
#include <iostream>
// a type to do something with
struct M { int i; };
// a type to represent the operations
struct Input_operation { M &m; int count; };
Input_operation operator << (M &m, int i) {
m.i = i;
return {m, 1};
}
Input_operation operator , (Input_operation op, int i) {
op.m.i += i;
op.count++;
return op;
}
int main() {
M m;
m << 1, 2, 3, 4, 5, 6;
std::cout << m.i << 'n';
}
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 重载操作程序时出错>>用于类中的字符串 memebr
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 呼叫运营商<<临时
- 对字符串进行位操作
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 我可以在 C++ 中的函数体之外进行操作吗?
- MPI突然停止了对多个核心的操作
- <<操作员在下面的行中工作
- 如何在信号处理程序和普通函数中对全局变量进行互斥读写操作
- 对字符数组中的元素执行逐位操作
- 如何在directx/c++中进行平移/缩放操作
- 逐位操作的隐式类型转换
- 为什么一个向量上的多线程操作很慢
- 排序时无法执行交换操作.我做的时候它会崩溃.为什么
- 位移操作和位掩码未检测到重复字符
- 如何进行特定的位操作?
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 字符串操作 - 字符计数
- c++11的特定过载<<操作人员