繁体   English   中英

正确转换fstream读写成员函数

[英]Proper casting for fstream read and write member functions

尽管关于reinterpret_cast的主题有很多行,以及它的糟糕程度,但我仍然对避免这种情况的最佳方法感到困惑,特别是在处理诸如从fstream进行读取和写入之类的功能时。 所以,这是我的困境...

假设我们有一个整数数组,我们希望用文件中的一些数据来填充。

std::ifstream iFile( ... );

// presume that the type of this array is not a matter of choice
int *a = new int[ 100 ]; 

我们可以通过几种不同的转换来阅读:

iFile.read( (char *)a, sizeof( int ) * 100 );
iFile.read( reinterpret_cast< char * >( a ), sizeof( int ) * 100 );
iFile.read( static_cast< char * >( static_cast< void * >( ( a ) ), sizeof( int ) * 100 );

第一个(C风格)已经过时,我们出于充分的理由在C ++中引入了新风格的演员表。 第二个是不可携带的,不提供任何保证。 第三篇是乏味的写作,破坏了乐趣。

除此之外,还有其他选择吗?

编辑:

目标是使代码尽可能地可移植且符合标准。

为什么不将a声明为char*

//int *a = new int[100]; 
char *a = new char[100];
iFile.read(a, 100 ); 

现在无需投放。


编辑:

好的,我阅读了您的评论和帖子中的评论行。 在这种情况下:

iFile.read(reinterpret_cast<char*>(a), sizeof(int)*100);

应该足够了。

但是,我个人会选择C样式转换:

iFile.read((char*)a, sizeof(int)*100);

那是因为我在这里看不到任何危险。 即使使用C-Style演员,一切似乎都还不错!


最好但不那么乏味的演员

定义此功能模板:

template<class To, class From>
To any_cast(From v)
{
    return static_cast<To>(static_cast<void*>(v));
}

然后使用它:

//`From` type will be inferred from the function argument. :-) 
iFile.read(any_cast<char*>(a), sizeof(int)*100);

看起来不错?

我认为可以将any_cast从任何类型转换为任何类型!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM