没有。 C++ 函数的返回类型只能根据显式模板参数或其参数的类型而有所不同。它不能根据其参数的值而变化。
但是,您可以使用各种技术来创建一个由其他几种类型组合而成的类型。不幸的是,这不一定对您有帮助,因为其中一种技术是 void * 本身,并且回到原来的类型会很痛苦。
但是,通过彻底解决问题,您可能会得到想要的结果。我想你会想使用你发布的代码,例如:
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 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的三个实现。