Search code examples
c++macrosconcatenationuser-defined-literals

How to compose stringification with user defined literal (UDL) in Macro?


How to use literal suffix for identifier transformed into literal string in MACRO by #identifier?

struct SomeType;
SomeType operator "" _udl(const char* self);

#define STRINGIFY_AS_UDL(id) /* #id _udl doesn't work */ /* How to have "id"_udl */ 

STRINGIFY_AS_UDL(foo) // -> "foo"_udl
STRINGIFY_AS_UDL(bar) // -> "bar"_udl
STRINGIFY_AS_UDL(42)  // -> "42"_udl

Solution

  • UDL operators are also "regular" functions, so you can call them instead:

    #define STRINGIFY_AS_UDL(id) operator ""_udl(#id)
    

    but you can use the token-pasting operator ##:

    #define STRINGIFY_AS_UDL(id) #id ## _udl
    

    or concatenation of adjacent strings:

    #define STRINGIFY_AS_UDL(id) #id ""_udl
    

    Note that any of the concatenation method would be required for template UDL for string (extension of gcc/clang):

    // gcc/clang extension
    template<typename Char, Char... Cs>
    /*constexpr*/ SomeType operator"" _udl();
    
    // Usage
    // "some text"_udl