C->C++ Automatically cast void pointer into Type pointer in C++ in #define in case of type is not given (C-style) [MSVS]


I've used the following C macro, But in C++ it can't automatically cast void* to type*.

#define MALLOC_SAFE(var, size) { \
    var = malloc(size); \
    if (!var) goto error; \

I know, I can do something like this:

#define MALLOC_SAFE_CPP(var, type, size) { \
    var = (type)malloc(size); \
    if (!var) goto error; \

But I don't want to rewrite a big portion of code, where MALLOC_SAFE was used.

Is there any way to do this without giving the type to the macro? Maybe some MSVC 2005 #pragma/__declspec/other ?

p.s.: I can't use C compiler, because my code is part (one of hundreds modules) of the large project. And now it's on C++. I know, I can build my code separately. But it's old code and I just want to port it fast.

The question is about void* casting ;) If it's not possible, I'll just replace MACRO_SAFE with MACRO_SAFE_CPP

Thank You!


  • I do not recommend doing this; this is terrible code and if you are using C you should compile it with a C compiler (or, in Visual C++, as a C file)

    If you are using Visual C++, you can use decltype:

    #define MALLOC_SAFE(var, size)                      \
    {                                                   \
        var = static_cast<decltype(var)>(malloc(size)); \
        if (!var) goto error;                           \