用户定义的文字运算符

now*_*owi 3 c++ c++11 c++17

如何在扩展为某些文字表达式的宏上使用用户定义的文字运算符?

例如:

std::string operator""_str(const char* sz, std::size_t len)
{
    return std::string(sz);
}
Run Code Online (Sandbox Code Playgroud)

其中的实现类似于:

#define expr "expression"
auto str = expr _str;
Run Code Online (Sandbox Code Playgroud)

cpp*_*ner 5

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

auto str = expr ""_str;
Run Code Online (Sandbox Code Playgroud)

would work.


Igo*_*nik 4

您需要另一个执行标记粘贴的宏:

#define CONCAT2(A, B) A##B
#define CONCAT(A, B) CONCAT2(A, B)
auto str = CONCAT(expr, _str);
Run Code Online (Sandbox Code Playgroud)

演示