[英]How to idiomatically convert ``char*`` to ``double*``
I'm relearning C++, and I'm trying to work with boost::iostreams::mapped_file
. 我正在重新学习C ++,我正在尝试使用
boost::iostreams::mapped_file
。 This class maps file data to char*
, I'd like to cast it to double*
(since I'm working with doubles). 这个类将文件数据映射到
char*
,我想将它转换为double*
(因为我正在处理双打)。
I could cast it using C-style cast: double* foo = (double*) data
, but I'm trying go use idiomatic C++, and C++ favours C++ casts like: static_cast
and so on. 我可以使用C风格的强制类型转换:
double* foo = (double*) data
,但我正在尝试使用惯用的C ++,而C ++更喜欢C ++强制转换,如: static_cast
等。
I came up with: 我提出了:
double* data = static_cast<double*>((void*)file.data());
(file->data returns char*
). (file-> data返回
char*
)。 Which really isnt cleaner. 哪个真的不干净。
Here is what I'm trying to do (this code works!): 这是我正在尝试做的(此代码有效!):
BOOST_AUTO_TEST_CASE(OpenMMapArray){
typedef boost::multi_array_ref<double, 3> arrayd3;
typedef std::array<size_t, 3> index3d;
index3d shape = {{ 20, 20, 20 }};
size_t size = sizeof(double)*std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<size_t>());
boost::iostreams::mapped_file file;
boost::iostreams::mapped_file_params params;
params.path = "/tmp/mmaptest-2";
params.mode = std::ios::in | std::ios::out;
params.new_file_size = size;
file.open(params);
double* data = static_cast<double*>((void*)file.data());
arrayd3 array(data, shape);
array[0][0][0] = 20;
array[0][1][0] = 19;
array[1][0][0] = 18;
array[0][0][5] = 17;
BOOST_CHECK(data[0] == 20);
BOOST_CHECK(data[20] == 19);
BOOST_CHECK(data[20*20] == 18);
BOOST_CHECK(data[5] == 17);
file.close();
}
In this particular case, you actually are trying to re-interpret the data as a different type. 在这种特殊情况下,您实际上是在尝试将数据重新解释为不同的类型。 So a
reinterpret_cast
is in order: 所以
reinterpret_cast
是有序的:
double* data = reinterpret_cast<double*>(file.data());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.