VTK 具有基本类型(float、int、double 等)的类型定义,并且它为每种类型分配一个整数。 它们被指定为 here .
函数 GetDataType()
,例如在 vtkDataArray
中,返回一个对应于其中一种类型的整数。
我想将该整数与基本数据类型(float、int、double)进行比较。
有没有办法轻松做到这一点?
我对它的用法是一个模板类,其参数 T 是一个标量。 我想检查数据集的标量点数据是否具有与 T 相同的数据类型。
现在,我所做的是字体大小比较:
vtkDataArray *scalars = image->GetPointData()->GetScalars();
if(scalars->GetDataTypeSize() != sizeof(T))
{
std::cerr<<"Incompatible types"<<std::endl;
}
但显然,float
和 int
的大小都是 4,所以它实际上不起作用。
有什么想法吗?
最佳答案
在从几个地方收集信息后,我得出结论,如果不自己在两个类型列表之间创建映射,就无法简单地编写它。
所以,这是我发现的最优雅的方式:
我用了norisknofun的 map 的思路,但是我倒过来了。
我没有使用 std::type_index()
,因为您似乎可以直接从 typeid()
的结果中获取 hash_code。
我将此映射放在一个将基本类型转换为 VTK 类型的函数中,因为它可以用于其他目的,而不仅仅是比较(参见我的 other post)。
#include <vtkType.h>
int GetVTKType(std::size_t hash_code)
{
static std::map<std::size_t, long> typeMap;
if(typeMap.empty())
{
typeMap[typeid(void).hash_code()] = VTK_VOID;
typeMap[typeid(char).hash_code()] = VTK_CHAR;
typeMap[typeid(signed char).hash_code()] = VTK_SIGNED_CHAR;
typeMap[typeid(unsigned char).hash_code()] = VTK_UNSIGNED_CHAR;
typeMap[typeid(short).hash_code()] = VTK_SHORT;
typeMap[typeid(unsigned short).hash_code()] = VTK_UNSIGNED_SHORT;
typeMap[typeid(int).hash_code()] = VTK_INT;
typeMap[typeid(unsigned int).hash_code()] = VTK_UNSIGNED_INT;
typeMap[typeid(long).hash_code()] = VTK_LONG;
typeMap[typeid(unsigned long).hash_code()] = VTK_UNSIGNED_LONG;
typeMap[typeid(float).hash_code()] = VTK_FLOAT;
typeMap[typeid(double).hash_code()] = VTK_DOUBLE;
typeMap[typeid(std::string).hash_code()] = VTK_STRING;
typeMap[typeid(long long).hash_code()] = VTK_LONG_LONG;
typeMap[typeid(unsigned long long).hash_code()] = VTK_UNSIGNED_LONG_LONG;
typeMap[typeid(int64_t).hash_code()] = VTK___INT64;
typeMap[typeid(uint64_t).hash_code()] = VTK_UNSIGNED___INT64;
}
return typeMap[hash_code];
}
因此,为了比较 vtk 数据类型和基本类型(我的模板参数 T),我这样做:
vtkDataArray *scalars = image->GetPointData()->GetScalars();
if(scalars->GetDataType() != GetVTKType(typeid(T).hash_code()))
{
std::cerr<<"Incompatible types"<<std::endl;
}
或者如果我想要像 norisknofun 那样的比较功能,我可以这样做:
template < class T >
bool is_same(long vtkType)
{
return vtkType != GetVTKType(typeid(T).hash_code())
}
// somewhere.cpp
if(!is_same<T>(scalars->GetDataType()))
{
std::cerr<<"Incompatible types"<<std::endl;
}
关于c++ - 比较vtk数据类型和基本数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36476714/