c++ - 在 C++ 中基于大小的运行时类型转换

标签 c++ templates casting

我正在尝试根据元素的大小恢复数组的类型。我想我不能为此使用模板。没有 switch 语句有没有办法实现这个?或者,如果没有 switch 语句是不可能的,有没有办法将 switch 语句嵌入到一个类(施法者)中。我喜欢 caster 类的想法,因为除了 copy 之外还有很多函数需要类似的转换。

copy_region(uint8_t *, int);
copy_region(uint16_t *, int);
copy_region(uint32_t *, int);

void copier(uint8_t *ptr_element, int sz_element) {
   copy_region( caster(sz_element, ptr_element), n);
}

我的switch方案是这样的:

void copier(uint8_t *ptr_element, int sz_element) {
   switch(sz_element){
     case 1: copy_region( uint8_t*(ptr_element), n); break;
     case 2: copy_region( uint16_t*(ptr_element), n); break;
     case 4: copy_region( uint16_t*(ptr_element), n); break;
   }
}

我还考虑过将操作定义为仿函数,这样我可能只有一个 switch 语句,但不同操作的参数非常不同。

编辑:

类型信息不会丢失。我正在尝试使用模板化缓冲区实现一个系统(库/框架)。我有一个基于 uint8_t 作为元素的基本缓冲区类。这个类存在是因为我需要将缓冲区插入到列表中。基本缓冲区类实现对这些缓冲区的操作。用户将缓冲区类型指定为缓冲区类的模板参数,但库只能看到基本缓冲区类和类型信息(元素大小足以推断类型)。

最佳答案

template<int sz_element> void copier(uint8_t *ptr_element); //no definition
template<1> void copier(uint8_t *ptr_element)
{copy_region(uint8_t*(ptr_element), n);}
template<2> void copier(uint8_t *ptr_element)
{copy_region(uint16_t*(ptr_element), n);}
template<4> void copier(uint8_t *ptr_element)
{copy_region(uint32_t*(ptr_element), n);}
template<8> void copier(uint8_t *ptr_element)
{copy_region(uint64_t*(ptr_element), n);}

如果 sz_element 在编译时未知,那么您必须像在 OP 中那样使用开关。

不过这并没有什么好处。为什么你有一个指向任意数据的 uint8_t*?摆脱它。

[编辑] 你说你有一个底层类是 uint8_t 的缓冲区,用户将使用带有类型信息的继承类。在这种情况下,要拥有理智的代码,您需要虚函数:

class base {
   vector<uint8_t> buffer;
public:
   virtual void copy()=0;
   virtual ~base() {}
};
template <class type>
class derived : public base {
public:
   virtual void copy() {}
   ~derived() {}
};

这将允许您的库在不知道类型的情况下使用函数,并且不会丢失任何类型信息。

关于c++ - 在 C++ 中基于大小的运行时类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8057603/

相关文章:

c++ - 在 Linux 中检测从管道/fifo 的另一端读取的尝试

c++ - Qt:检查文件夹中的文件是否已更改

c++ - 关于模板实例化点的一些问题

c++ - 模板类中特殊函数的声明

javascript - JSON 模板引擎

c++ - 使用getline时哪种方式更好?

c++ - Scons 没有指定 CPPPATH,仍然可以检测到 .h 依赖吗?

MySQL返回与搜索条件不匹配的多行

c++ - const_cast 是如何工作的?

java - 对 Java 中的后期绑定(bind)/转换感到困惑