使用简单实例作为C遗产函数的参数

Using simple instance as parameter to a c legacy function

本文关键字:遗产 函数 参数 简单 实例      更新时间:2023-10-16

我为4*4矩阵定义了一个助手类:

class BCMatrix {
  public:
    float matrix[4][4];
  void do_something_nice();
  void do_something_else();
};

我有另一个来自C库的功能,无法被更改:

void copy_m4_m4(float r[4][4], float f[4][4]);

在我的bcmatrix类中,我可以做这样的事情:

float mat[4][4];
BCMatrix obmat;
copy_m4_m4(obmat.matrix, mat);

,但我实际上希望能够做这样的事情:

BCMatrix mat;
BCMatrix obmat;
copy_m4_m4(obmat, mat);

当然我可以添加一个操作员=或这样的简单函数:

void copy_m4_m4(BCMatrix &to, BCMatrix &from)
{
    copy_m4_m4(t.matrix, f.matrix);
}

但我想知道是否有任何优雅(正确且令人愉快的(方式告诉编译器BCMATRIX实际上只是浮点[4] [4],以便使用一些额外的方法,因此可以直接将其用作参数copy_m4_m4((函数?

您需要一个隐式转换运算符,如以下内容。有关更多详细信息,请参见用户定义的转换。

class BCMatrix {
public:
  using float_t = float[4];  // Typedef required because of array
  operator float_t*() { return matrix; } // The conversion operator itself
    float matrix[4][4];
  void do_something_nice();
  void do_something_else();
};
// Mock, to make sure it's working as planned
void copy_m4_m4(float r[4][4], float f[4][4]) {
  for(auto i = 0; i < 4; ++i) {
    for(auto j = 0; j < 4; ++j) {
      std::cout << r[i][j] << ", ";
    }
    std::cout << std::endl;
  }
}
int main() {
  std::string testString = "testing";
  // Test: fill the source array
  BCMatrix obmat;
  for(auto i = 0; i < 4; ++i) {
    for(auto j = 0; j < 4; ++j) {
      obmat[i][j] = 5 * i * j;
    }
  }
  // Final step in proving it works: call the [4][4] function
  BCMatrix mat;
  copy_m4_m4(obmat, mat);
}