gpt4 book ai didi

<< 运算符的 c++11 特定重载

转载 作者:行者123 更新时间:2023-11-28 02:17:51 24 4
gpt4 key购买 nike

对于一项作业,我必须按照一些明确的说明编写一个矩阵类。其中一条指令是重载 << operator ,这样我们就可以以这种方式读取矩阵 m 的值:

m << 1,2,3,4,5,6;

我尝试研究具有可变参数的函数,但后来我发现我无法使用可变数量的参数重载运算符。

我尝试查看 std::initializer_list ,使用来自 cpp reference 的一些引用代码

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';
}

关于<< 运算符的 c++11 特定重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33490124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com