c++11的特定过载<<操作人员

c++11 specefic overload of << operator

本文关键字:lt 操作 c++11      更新时间:2023-10-16

对于一个赋值,我必须按照一些明确的说明编写一个矩阵类。指令之一是使<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';
}