c++genericsreturn-type

Howto: C++ function that adjusts its return type to the callers needs


I have a malloc like function:

void * MyMalloc(size_t size) { return malloc(size); }

Now to use this for let's say a char * type;

char * charPointer = static_cast<char *>(MyMalloc(100));

How to get rid of the cast?

I can do this:

template<typename T> T MyMalloc(size_t size) {return static_cast<T>(MyMalloc(size));}

And the callling code is:

char * charPointer = MyMalloc<char *>(100);

This looks better, but is there a way to let the compiler do this for me? Similar to auto, but my understanding of auto is that auto is determined by the return / assignment type not the needs of the caller.

What I want the calling code to look like is :

char * charPointer = MyMalloc(100);

Of course code like this would not work (and I would not want it to):

int val = MyMalloc(100);

I am not sure this can be done, but it it can be done, I'm sure somebody here knows. Ty


Solution

  • You can use a class type for this. Classes can have a template conversion operator that will deduce the type you whish to convert to based on the expression it is used in. That gives you a class that looks like

    class MyMalloc
    {
    public:
        MyMalloc(std::size_t size) : ptr(malloc(size)) {}
        template <typename T>
        operator T() { return static_cast<T>(ptr); }
    private:
        void* ptr;
    };
    

    and this lets you use it like

    int main()
    {
        char * charPointer = MyMalloc(100);
    }
    

    which you can see working in this live example.