gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 01:20:48 26 4
gpt4 key购买 nike

我对重载规则有点困惑,

假设有以下文字运算符,

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(无符号长整型参数),则 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com