基于字符串的用户定义文字是否可以强类型化?

Mar*_*tos 10 c++ user-defined-literals variadic-templates c++11

C++中新的用户定义的文字概念提出了一些非常有趣的字符串文字用法,例如:

"Goodbye %s world"_fmt("cruel");
"Goodbye %s world"_fmt(123); // Error: arg 1 must be convertible to const char*

R"(point = \((\d+), (\d+)\))"_re; // Builds DFA at compile-time.

typedef table<
    column<"CustId"_name   , std::string>,
    column<"FirstName"_name, std::string>,
    column<"LastName"_name , std::string>,
    column<"DOB"_name      , date       >
> Customer;
Run Code Online (Sandbox Code Playgroud)

但是,当我在gcc中构建这些类型的构造时,例如:

template <char... Chars> Name<Chars...> operator "" _name() {
    return Name<Chars...>();
}

auto a = 123_name;    // OK
auto b = "abc"_name;  // Error
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

…unable to find string literal operator ‘operator"" _name’ with ‘const char [4]’, ‘long unsigned int’ arguments
Run Code Online (Sandbox Code Playgroud)

从阅读开始,我猜测variadic-template表单不适用于从字符串文字派生的UDL.

  1. 实际上是否使用可变参数模板表单无法解析字符串文字?
  2. 如果是这样,有没有人能够深入了解为什么这种有用的UDL形式被排除在标准之外?

R. *_*des 8

你是对的.字符串文字不能与可变参数模板形式一起使用(§2.14.8/ 5):

如果L用户定义的字符串文字,则令str为没有其ud后缀的文字,并且lenstr中的代码单元数 (即,其长度不包括终止空字符).文字L被视为表格的调用

operator "" X (str, len)
Run Code Online (Sandbox Code Playgroud)

我已经推翻了提案文件(我能找到的最新版本是N2750)并且无法找到不允许使用可变参数模板形式的解释.

  • 允许使用可变参数形式的所有用户定义文字都限于基本源字符集(仅仅因为语法不允许在整数或浮点数中使用任何其他内容).字符串文字没有这种限制,因此使用多字节源/执行编码时,字符串文字中的c-chars可能无法表示为单个字符.这可能与决定不允许使用字符串文字的可变形式有关. (3认同)