运行时类型在c++中的转换,如何
runtime type conversion in C++, how?
我试图分析一个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);
}
这假设您只知道调用代码中的返回类型。这可能适用于你的情况,也可能不适用。另外,上面的代码是否能按原样编译也是值得怀疑的。
相关文章:
- 如何使用OpenCV将RBG图像转换为HSV,并将H、S和V值保存为C++中的3个独立图像
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 如何修复函数样式强制转换或类型构造的预期"("?
- 如何理解将半精度指针转换为无符号长指针和相关的内存对齐
- 如何将这个C++哈希表转换为动态扩展和收缩,而不是使用硬设置的最大值
- C++十进制到二进制,如何转换
- 如何将一个ostringstream十六进制字符串字符对转换为单个unit8t等价的二进制值
- 如何使用Rcpp将R函数转换为C++函数
- 我正在尝试使用 c++ 创建一个货币转换程序,我不知道如何继续
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将模板转换为C++11之前的模板
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- 如何将这个std::字符串转换为std::基本字符串
- 如何将真正的字符串从python c-api转换为python脚本
- 为什么这种隐式转换如何以及为什么起作用
- 隐式转换如何用于非类型模板参数
- 从字符串到char[]的转换如何使其变长?
- 从未知指针到类的强制转换;如何检查有效性
- 此数组转换如何工作(使用字符串从小写到大写)