C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了根据数据返回不同的数据类型(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函数的返回类型只能根据显式模板参数或其参数的类型而有所不同.它不能根据其参数的值而变化.

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

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

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)全部内容,希望文章能够帮你解决根据数据返回不同的数据类型(C)所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。