根据数据返回不同的数据类型(C ++) [英] Returning different data type depending on the data (C++)
问题描述
反正还有做类似的事情吗?
Is there anyway to do something like this?
(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 ++函数的返回类型只能根据显式模板参数或其参数的 types 进行更改。它不能根据其参数的 value 而有所不同。
No. The return type of a C++ function can only vary based on explicit template parameters or the types of its arguments. It cannot vary based on the value of its arguments.
但是,您可以使用多种技术来创建一个类型,该类型是多个值的并集其他类型。不幸的是,这不一定对您有帮助,因为这样一种技术本身是无效的,而且回到原始类型将很痛苦。
However, you can use various techniques to create a type that is the union of several other types. Unfortunately this won't necessarily help you here, as one such technique is void * itself, and getting back to the original type will be a pain.
但是,通过转动从内而外的问题,您可能会得到想要的。我想您想使用发布的代码,例如:
However, by turning the problem inside out you may get what you want. I imagine you'd want to use the code you posted as something like, for example:
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本身成为模板,然后根据深度使用开关对其进行包装:
Because C++ needs to know the type of p_pixels at compile time, this won't work as-is. But what we can do is make bitmap_operation itself be a template, then wrap it with a switch based on the depth:
template<typename PixelType>
void bitmap_operation_impl(void *data, int width, 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 depth, int width, int height) {
if (depth == 8)
bitmap_operation_impl<uint8_t>(data, width, height);
else if (depth == 16)
bitmap_operation_impl<uint16_t>(data, width, height);
else if (depth == 32)
bitmap_operation_impl<uint32_t>(data, width, height);
else assert(!"Impossible depth!");
}
现在,编译器将自动为您生成bitmap_operation_impl的三个实现。
Now the compiler will automatically generate three implementations for bitmap_operation_impl for you.
这篇关于根据数据返回不同的数据类型(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!