struct mat4x4
{
float m[4][4] = {0};
};
基本上,我有乘以 4x4 矩阵的函数。
mat4x4 matrix_matrix(mat4x4 m1, mat4x4 m2)
{
mat4x4 product.m[someValue][someValue] = do_calculations_and_get_product();
return product;
}
所以我的想法是采用第三个 mat4x4
作为引用参数,将乘积保存在新矩阵中并返回该矩阵。但这意味着在调用它时必须传递第三个参数。我希望能够通过仅传递 2 个矩阵来调用它,并期望将乘积矩阵作为输出,并且如果给出第三个矩阵,我希望它将结果保存到第三个矩阵并返回该矩阵。
通过阅读其他一些帖子,我想到了这个
mat4x4 matrix_matrix(mat4x4 m1, mat4x4 m2, const mat4x4 & m3 = mat4x4{})
{
m3.m[somevalue][somevalue] = do_calculations_and_get_product();
return m3;
}
但我收到错误:表达式必须是可修改的左值
,m3
下有一条红色摆动线。我真的不知道自己在做什么,需要有人帮助我。谢谢
删除 const 会出现以下错误:
initial value of reference to non-const must be an lvalue
在函数定义中的 mat4x4
{} 下有一条红色摆动线。
最佳答案
有了支持 C++17 的编译器,使用 std::Optional
和 std::reference_wrapper
就变得很简单了。隐式转换会为您完成所有艰苦的工作。
#include <optional>
#include <utility>
#include <functional>
struct mat4x4
{
float m[4][4] = {0};
};
mat4x4 matrix_matrix(mat4x4 m1, mat4x4 m2,
std::optional<std::reference_wrapper<mat4x4>
> m3=std::nullopt)
{
mat4x4 new_m;
// Calculate something in new_m;
if (m3)
*m3=new_m;
return new_m;
}
void test()
{
mat4x4 m1, m2, m3, mret;
mret=matrix_matrix(m1, m2);
mret=matrix_matrix(m1, m2, m3);
}
关于c++ - 为函数提供默认参数,但该参数是一个结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64633154/