微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

根据数据返回不同的数据类型(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的三个实现.

原文地址:https://www.jb51.cc/c/111630.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐