c++ - VC++ 2008 中的模板数组

标签 c++ templates

我正在尝试使用 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/

相关文章:

c++ - 如何在C++中从O(n)的关联NxN矩阵中删除行和列?

c++ - 通过 "Value Template Argument"与常规数组在堆栈中分配内存

C++ 如何重载一个函数,该函数将不同模板对象的迭代器作为参数?

c++ - 如何使用参数数量定义 std::tuple<...>

c++ - 表达式 SFINAE 重载传递函数指针的类型

c++ - 使用带有嵌套结构的模板化 lambda 时的类型推导 + 分析可能未使用的程序集输出

c++ - 有什么方法可以跳过std::visit中一些变体类型的重载组合?

c++ - 遍历所有 bool 组合

C++ 成员模板特化语法

c++ - 将异常转换为可选的 : cant resolve overloaded function type