<< 运算符的 c++11 特定重载
c++11 specefic overload of << operator
对于作业,我必须按照一些明确的说明编写矩阵 class。其中一条指令是重载 << operator ,这样我们就可以以这种方式读取矩阵 m 的值:
m << 1,2,3,4,5,6;
我尝试研究具有可变参数的函数,但后来我发现我无法使用可变数量的参数重载运算符。
我尝试使用 cpp reference
中的一些参考代码查看 std::initializer_list
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;
}
所以我的问题是,我可以使用哪些 class/type 参数来实现这一点,我想到的选项没有用,或者我没有以正确的方式使用它们。
非常感谢。
编辑:
在@bames53 给出了很好的回答后,我尝试合并并且效果很好!
<<
的优先级高于 ,
所以你的表达式 m << 1,2,3,4,5,6
所做的是:
((((((m << 1), 2), 3), 4), 5), 6)
换句话说,你需要m << 1
到return一个表示已经读入1
并准备读入2
的操作的对象。这种事情通常是用 'expression templates' 完成的,尽管在你的情况下你并不真正需要模板。
您的用法将有一个不同之处在于您确实需要在进行过程中修改对象,而通常的表达式模板是惰性操作的,等待它们的对象转换为最终结果类型后再实际执行工作。
#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';
}
对于作业,我必须按照一些明确的说明编写矩阵 class。其中一条指令是重载 << operator ,这样我们就可以以这种方式读取矩阵 m 的值:
m << 1,2,3,4,5,6;
我尝试研究具有可变参数的函数,但后来我发现我无法使用可变数量的参数重载运算符。
我尝试使用 cpp reference
中的一些参考代码查看 std::initializer_liststd::vector<float> mat;
Mat<M,N>& operator<<(std::initializer_list<float> l)
{
this->mat.insert(this->mat.begin(),l.begin(),l.end());
return *this;
}
所以我的问题是,我可以使用哪些 class/type 参数来实现这一点,我想到的选项没有用,或者我没有以正确的方式使用它们。
非常感谢。
编辑: 在@bames53 给出了很好的回答后,我尝试合并并且效果很好!
<<
的优先级高于 ,
所以你的表达式 m << 1,2,3,4,5,6
所做的是:
((((((m << 1), 2), 3), 4), 5), 6)
换句话说,你需要m << 1
到return一个表示已经读入1
并准备读入2
的操作的对象。这种事情通常是用 'expression templates' 完成的,尽管在你的情况下你并不真正需要模板。
您的用法将有一个不同之处在于您确实需要在进行过程中修改对象,而通常的表达式模板是惰性操作的,等待它们的对象转换为最终结果类型后再实际执行工作。
#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';
}