c++ - c++0x 中用户定义文字的重载规则

标签 c++ c++11 user-defined-literals

我对重载规则有点困惑,

假设有以下文字运算符,

unsigned long long operator "" _xx(unsigned long long cooked_literal_int); //1
unsigned long long operator "" _xx(const char * raw_literal_string); // 2
unsigned long long operator "" _xx(long double cooked_literal_double); // 3

如果同时定义了 1、2 和 3,则重载是显而易见的,

13_xx //call 1
13.5_xx //call 3

如果定义了 1 和 2,

13_xx //call 1
13.5_xx //call 2

如果定义了 2 和 3

13_xx // call 2 or 3??
13.5_xx // call 3

困惑来自最新的 c++0x 标准 n3225 2.14.8/3,

If L is a user-defined-integer-literal, let n be the literal without its ud-suffix. If S contains a literal operator with parameter type unsigned long long, the literal L is treated as a call of the form

operator "" X (n ULL)

Otherwise, S shall contain a raw literal operator or a literal operator template (13.5.8) but not both. If S contains a raw literal operator, the literal L is treated as a call of the form

operator "" X ("n")

Otherwise (S contains a literal operator template), L is treated as a call of the form

operator "" X <’c1’, ’c2’, ... ’ck’>()

where n is the source character sequence c1c2...ck.

这表示,如果存在 1(无符号 long long 参数),则 13_xx 应调用 1,否则,13_xx 应调用 2。从 13.5.8 开始,

In particular, they are looked up like ordinary functions and function templates and they follow the same overload resolution rules.

根据我的理解,如果1不存在,13_xx可以隐式转换为double并调用3。

因此,如果 1 不存在,则从标准描述来看,2 和 3 在某种程度上都是有效的。

希望有人能帮我解开疑惑。非常感谢。

最佳答案

我相信 13.5.8/7 澄清了这个问题:

Note: literal operators and literal operator templates are usually invoked implicitly through user-defined literals (2.14.8). However, except for the constraints described above, they are ordinary namespace-scope functions and function templates. In particular, they are looked up like ordinary functions and function templates and they follow the same overload resolution rules.

根据我的理解,常规重载解析规则仅在通过用户定义的文字在隐式调用外部调用时才对文字运算符隐含。

所以我认为如果定义了 2 和 3,13_xx 会调用 2(原始文字运算符)。

关于c++ - c++0x 中用户定义文字的重载规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4385297/

相关文章:

c++ - 使用 OpenGL 将位图文本居中到矩形

c++ - 指针的类型

c++ - 使用可变参数模板时出现意外的隐式转换?

c++ - 为什么非下划线名称保留给 UDL 的实现而不是相反?

c++ - 宏定义中预处理器标记周围有两个双引号

c++ - 如何在 wt(c++) 创建后更新网页

c++ - %*.*d 在 printf() 中如何工作?

c++ - 为 UDF std::unordered_map 提供 ":"运算符?

C++在成员变量中保存不同类型数据的优雅方式

c++ - 用户定义的字符串文字与常量字符串的比较