正确转换fstream读写成员函数

时间:2011-01-12 19:16:09

标签: c++ fstream reinterpret-cast

虽然有很多关于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 ++中引入了新的样式,这是有充分理由的。第二个是不可移植的,不提供任何保证。第三个是编写和破坏乐趣的乏味。

有没有替代方案,我应该怎么做呢?

编辑:

目标是实现尽可能便携和符合标准的代码。

1 个答案:

答案 0 :(得分:4)

为什么不将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可用于从任何类型转换为任何类型!