5

考虑以下代码

#include<algorithm>
#include<iostream>
#include<array>

void show(double x[2][2]) {
  std::cout<<x[0][0]<<", "<<x[0][1]<<std::endl
           <<x[1][0]<<", "<<x[1][1]<<std::endl;
}

int main() {
  std::array<double, 4> y = {1, 2, 3, 4};  
  double x[2][2];

  // it is safe to copy because x[2][2] consists of
  // four contiguous blocks of memory in row-major order

  std::copy(y.begin(), y.end(), &x[0][0]);

  show(x); // this, obviously, works as expected

  // but how can I cast y, or y.data(),
  // or y.begin() to use the function foo?    
  // show(y); 
}

我正在使用一个遗留库,其中有很多函数参数x[a][b]。但是,我的代码依赖于线性数据表示(也就是说,我只使用 C++“线性”容器,例如std::array<T, N>)。

想象一下,经过费力的计算,我已经到达了std::array<double, 2>包含我需要的数据的代码点,现在我需要调用foo这些数据。

我怎样才能“铸造”(因为没有更好的词)底层容器,以便我可以调用期望 a 的遗留函数double[2][2]

我真的不想复制(如示例所示),因为诸如此类的遗留函数foo被调用了数十万次。

作为一个极端的优点,我想将这些遗留函数包装在一个类似 C++ 算法的接口后面;类似于:

std::vector<std::array<double, 4>> z;
fooify(z.begin(), z.end()); // calls foo(zi) for each zi in z

编辑:一些答案

感谢@6502,我从以下解决方案开始:

#include<algorithm>
#include<iostream>
#include<array>

namespace legacy {
void show(double x[2][2]) {
  std::cout<<x[0][0]<<", "<<x[0][1]<<std::endl
           <<x[1][0]<<", "<<x[1][1]<<std::endl;
}
}

template<size_t N, typename Container>
void show(Container& y) {
  return legacy::show(reinterpret_cast<double(*)[N]>(y.data()));
}

int main() {
  std::array<double, 4> y = {1, 2, 3, 4};  
  show<2>(y);
}

它按预期工作——当然,我可以自动推断出“重塑”因子(在本例中为 2,但在一般情况下会有所不同)。

然后我会尝试将这个“重构”的函数合并到一个算法中。

为了完整起见,我添加了编译细节(OS X 10.7.4 using GCC 4.8.1):

$ g++ example.cpp -std=c++11 -Wall -Wextra
$ ./a.out                                                 
1, 2
3, 4
4

1 回答 1

3

使用 C 风格的强制转换

show((double (*)[2])y.data());

或者reinterpret_cast如果您想输入更多内容,请使用

show(reinterpret_cast<double (*)[2]>(y.data()));
于 2013-10-13T20:38:36.130 回答