Search code examples
c++return-value

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;
}

Thanks


Solution

  • 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]);
    }
    

    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!");
    }
    

    Now the compiler will automatically generate three implementations for bitmap_operation_impl for you.