运行时类型在c++中的转换,如何

runtime type conversion in C++, how?

本文关键字:转换 如何 类型 c++ 运行时      更新时间:2023-10-16

我试图分析一个geotiff文件,非常简单,只是试图获得所有的标签信息。我知道有libtiff和libgeotiff这样的库可用。我要做的很简单:读出所有的标签。

标签结构为:

struct ifd_entry
{
_int16 tag_id;
_int16 field_type;
_int16 field_count;
_int16 field_offset;
};

字段类型为int16,代表int8、int16、int32、float、double等格式。field_count表示该类型中数据的数量。Field_offset表示字段数据在文件中的位置,从文件开头开始。

我想做的是检索标记和它指向的字段数据。我想用一种简洁的c++方式来写,但是我不知道怎么做。似乎我无法避免使用switch语句来分别处理每种类型:

class ifd
{
   ifd_entry hd;
   char *pfield;
public:   
   ifd(ifd_entry hd0,char *p); //allocate and copy the field data
   void print(); //print the ifd_entry and its field, have to use switch to cast to the correct type;
};

这可能是微不足道的,但我想知道c++中处理此类问题的整洁方式是什么。谢谢你。

如果类型数量固定且较短,则使用Boost.Variant。在可能的类型上有一个变体,然后可以应用访问者模式来打印字段。内部实现可能与您当前所做的没有太大不同,但我发现它更符合习惯。

在这里使用switch语句似乎是最合适的。

std::ifstream instream("settings.txt");
template<> id<_int8> {enum{value=1};};
template<> id<_int16> {enum{value=2};};
template<> id<_int32> {enum{value=2};};
template<class TYPE>
std::vector<TYPE> read(const ifd_entry& entry) {
    assert(id<TYPE>::value == entry.tag_id);
    instream.seek(entry.field_offset);
    std::vector<TYPE> result.resize(entry.field_count);
    instream.read((char*)(TYPE*)(&result[0]), sizeof(entry.field_type)*entry.field_count);
    return result;
}
int main() { 
    ifd_entry entry;
    // read in entry
    // you know it points to _int32's because it's player's scores
    std::vector<_int32> result = read<_int32>(entry);
}

这假设您只知道调用代码中的返回类型。这可能适用于你的情况,也可能不适用。另外,上面的代码是否能按原样编译也是值得怀疑的。