根据数据返回不同的数据类型(C)
发布时间:2020-12-16 03:23:02 所属栏目:百科 来源:网络整理
导读:有没有办法做这样的事情? (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函数的返回类型只能根据显式模
有没有办法做这样的事情?
(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的三个实现. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |