Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

User-defined Literal Operator on Macros

Tags:

c++

c++11

c++17

How does one use a user-defined literal operator on a macro that expands to some literal expression?

e.g.:

std::string operator""_str(const char* sz, std::size_t len)
{
    return std::string(sz);
}

Where implementation is something like:

#define expr "expression"
auto str = expr _str;
like image 518
nowi Avatar asked Nov 07 '19 04:11

nowi


2 Answers

Adjacent string literals are automatically concatenated ([lex.ext]/8), so

auto str = expr ""_str;

would work.

like image 111
cpplearner Avatar answered Oct 08 '22 16:10

cpplearner


You need another macro that performs token pasting:

#define CONCAT2(A, B) A##B
#define CONCAT(A, B) CONCAT2(A, B)
auto str = CONCAT(expr, _str);

Demo

like image 37
Igor Tandetnik Avatar answered Oct 08 '22 17:10

Igor Tandetnik