6

尽管关于 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++ 中引入了新的风格转换,这是有充分理由的。第二个是不可移植的,不提供任何保证。第三个写起来很乏味,破坏了乐趣。

有没有其他选择,我应该怎么做?

编辑:

目标是实现代码尽可能可移植和符合标准。

4

1 回答 1

5

你为什么不声明achar*,像这样:

//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可以用来从任何类型转换为任何类型!

于 2011-01-12T19:20:47.187 回答