Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading