根据数据返回不同的数据类型(C)

有没有办法做这样的事情?
(correct pointer datatype) returnPointer(void* ptr,int depth)
{

    if(depth == 8)
        return (uint8*)ptr;
    else if (depth == 16)
        return (uint16*)ptr;
    else
        return (uint32*)ptr;
}

谢谢

解决方法

否.C函数的返回类型只能根据显式模板参数或其参数的类型而有所不同.它不能根据其参数的值而变化.

但是,您可以使用各种技术来创建一种类型,它是几种其他类型的联合.不幸的是,这不一定会帮助你,因为这样一种技术是无效的*本身,回到原来的类型将是一个痛苦.

但是,通过将问题内向外,您可以获得所需的内容.我想象你想使用你发布的代码,例如:

void bitmap_operation(void *data,int depth,int width,int height) {
  some_magical_type p_pixels = returnPointer(data,depth);
  for (int x = 0; x < width; x++)
    for (int y = 0; y < width; y++)
      p_pixels[y*width+x] = some_operation(p_pixels[y*width+x]);
}

因为C在编译时需要知道p_pixels的类型,所以不会按原样工作.但是我们可以做的是使bitmap_operation本身是一个模板,然后根据深度用一个开关包装它:

template<typename PixelType>
void bitmap_operation_impl(void *data,int height) {
  PixelType *p_pixels = (PixelType *)data;
  for (int x = 0; x < width; x++)
    for (int y = 0; y < width; y++)
      p_pixels[y*width+x] = some_operation(p_pixels[y*width+x]);
}

void bitmap_operation(void *data,int height) {
  if (depth == 8)
    bitmap_operation_impl<uint8_t>(data,width,height);
  else if (depth == 16)
    bitmap_operation_impl<uint16_t>(data,height);
  else if (depth == 32)
    bitmap_operation_impl<uint32_t>(data,height);
  else assert(!"Impossible depth!");
}

现在,编译器将为您自动生成bitmap_operation_impl的三个实现.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...