我正在尝试使用 VC++ 打开包含一些数字的原始数据文件。 数字可以是 8/16/24 位。对于给定的文件,我有先验知识。
我可以使用 C++ 模板创建数组变量来存储根据位深度从文件中读取的数字吗?这段伪代码的内容:
if(BitDepth==8)
{
CTemplate<unsigned byte> data; // data type should be unsigned byte
Read8Bit(data);
//.. various ops to read 8 bit data
}
if(BitDepth==16)
{
CTemplate<unsigned short> data; // data type should be unsigned short
Read16Bit(data);
//.. various ops to read 16 bit data
}
if(BitDepth==24)
{
CTemplate<unsigned int> data; // data type should be unsigned int
Read24Bit(data);
//.. various ops to read 24 bit data
}
//Later use 'data' out of scope of if() conditionals
当然,稍后必须在 if() 条件语句的范围之外使用模板变量“data”。所以我需要将“数据”声明为全局(例如,在 header 中)。我在这里失去了踪迹......
最佳答案
除非位深度是编译时常量,否则您有两个选择:
1) 使用运行时变量实现对象(可以使用模板而不是运行时多态性生成实现,但要使用它们,您必须 type erase 到虚拟接口(interface)或打开运行时位深度,以便选择其中)。
2) 使所有调用函数都将位深度作为模板参数,直到执行上述运行时变量的某个级别 -> 特定位深度模板映射(至少在 main 中你必须这样做)
是的,你可以有(常量)整数模板参数和它们的偏特化。
关于c++ - VC++ 2008 中的模板数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1424454/