c++macrossdl

Is it possible to use a macro variable next to already existing text


I want to use unique pointers with sdl2, but the declaration to make them work can get lengthy, so I was trying to use a #define that would allow me to simply insert the type I want to extract and use that.

But I ran in the simple issue that the macro parameter is not recognized when it is adjacent to other text. For example in the following declaration :

#define SDL(type) SDL_type

the type in the replacement text is treated as part of a larger word instead of as a macro parameter. The intent is that SDL(int) would become SDL_int, but instead it becomes SDL_type, ignoring the supplied argument.

Is there some kind of flag or token that would allow me to just "insert" the content of the variable next to already existing text without adding anything to the define ?

Here is how the compiler expands a similar macro. The compiler's reported expansion Instead of SDL_(Texture) and SDL_Destroy(Texture), the desired expansion is SDL_Texture and SDL_DestroyTexture.


Solution

  • You probably want

    #define UNIQ(type) std::unique_ptr<SDL_##type, decltype(&SDL_Destroy##type)>
    

    so UNIQ(Texture) becomes

    std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>
    

    but as the number of type is limited, I suggest to use typedef instead:

    using UniqueTexture = std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>;
    using UniqueRenderer = std::unique_ptr<SDL_Renderer, decltype(&SDL_DestroyRenderer)>;
    

    Providing a functor instead of pointer on function seems even more appropriate.