我正在尝试定义用户定义的字符串文字模板。
该代码片段不应该起作用吗?/ 为什么不起作用?
template<char...>
constexpr
int operator ""_x () {
return 0;
}
int x = "abc"_x;
Run Code Online (Sandbox Code Playgroud)
运算符声明被编译器“接受”为有效 - C++ 对用户定义的文字非常严格,任何与规范声明的偏差都会被诊断为错误。因此,接受该声明对我来说表明它很好 - 正如我所期望的 - 但我尝试过的编译器(GCC、Clang、MSVC - godbolt.org 上的所有trunk)都没有编译使用下一个定义运算符,其中 Clang 和 MSVC 找不到匹配的文字运算符,而 GCC 给出了一个令人惊讶的奇怪错误(你可以在godbolt.org上看到完整的错误),其中部分:
(...)
<source>:7:9: error: type/value mismatch at argument 1 in template parameter list for 'template<char ...<anonymous> > constexpr int operator""_x()'
7 | int x = "abc"_x;
| ^~~~~~~
<source>:7:9: note: expected a constant of type 'char', got 'char'
Run Code Online (Sandbox Code Playgroud)
(编译器说)我预料到了char,但是我得到了char......Maaan......我不知道现在该怎么办!- …