问题描述
我正在学习用户定义的文字,并与以下测试代码混淆:
I'm learning about user-defined literals, and confused with the following test code:
std::chrono::seconds operator"" _s(unsigned long long s) {
return std::chrono::seconds(s);
}
std::string operator"" _str(const char *s, std::size_t len) {
return std::string(s, len);
}
int main() {
auto str = "xxxxx"_str;
std::cout << str.size() << std::endl; // works
auto sec = 4_s;
std::cout << sec.count() << std::endl; // works
std::cout << "xxxxx"_str.size() << std::endl; // works
std::cout << 4_s.count() << std::endl; // does **NOT** work!
return 0;
}
编译器给出以下错误消息:
The compiler gives the following error message:
似乎需要 _s.count 作为用户定义的文字。另外,浮点文字的行为类似于整数文字。
It seems that it takes _s.count as a user-defined literal. Also, a floating-point literal behaves like an integer literal.
为什么用户定义的整数文字和字符串文字具有不同的行为?
Why do user-defined integer literals and string literals have different behavior?
推荐答案
这就是浮点数文字的工作方式!
That's how floating point literals work!!
添加一对括号,它应该可以正常工作:
Add a pair of parentheses and it should work:
std::cout << (4_s).count();
或者将它们分开(以防止编译器将其解释为格式不正确的分数常量浮动)点文字):
Or alternatively, separate them (to stop the compiler from interpreting it as an ill-formed fractional constant floating point literal):
std::cout << 4_s .count();
// ^ Space here!
参考:
在 注释 中>以上参考文献的部分,
In the Notes section of the reference above,
long double operator""_E(long double);
long double operator""_a(long double);
int operator""_p(unsigned long long);
auto x = 1.0_E+2.0; // error
auto y = 1.0_a+2.0; // OK
auto z = 1.0_E +2.0; // OK
auto w = 1_p+2; // error
auto u = 1_p +2; // OK
因此,当涉及到点时,使用作为小数点,它必须与后面的任何东西分开,否则将被视为浮点数的一部分。
So when it comes to dot, which is used as decimal point, it must be separated from anything behind, or it'll be treated as part of the floating point number.
我已经从CppReference测试了上面的示例,并得到了非常 silimar错误消息:
I have tested the example above from CppReference and got a very silimar error message:
test.cpp:19:10: error: unable to find numeric literal
operator 'operator""_E+2.0'
^^^^^^
auto x = 1.0_E+2.0; // error
要点 _E + 2.0
被视为一个整体 ud后缀?
我最初的解释尝试是在这篇文章的中找到。
My original explanation attempt can be found in the revision history of this post.
这篇关于为什么用户定义的字符串文字和整数文字具有不同的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!