简体   繁体   English

C++中的操作符“”是做什么的?

[英]What does the operator“” do in C++?

How do you call this operator?你怎么称呼这个运营商?

Can you use it for things other than the creation of custom literals?除了创建自定义文字之外,您可以将它用于其他事情吗?

Example usage: (see cppreference )示例用法:(参见cppreference

constexpr long double operator"" _deg ( long double deg )
{
    return deg * 3.14159265358979323846264L / 180;
}

The primary usage of this operator"" is the creation of user-defined-literals.operator""的主要用途是创建用户定义的文字。 From the reference :参考

Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix.通过定义用户定义的后缀,允许 integer、浮点、字符和字符串文字生成用户定义类型的对象。


You can call this operator as you would any other overloaded operator:您可以像调用任何其他重载运算符一样调用此运算符:

std::cout << 42.5_deg;                // with convenient operator syntax
std::cout << operator"" _deg(42.5);   // with an explicit call

Not entirely unrelated: as pointed out in the comments to your question, this example is badly named.并非完全不相关:正如对您问题的评论中指出的那样,这个例子的名字很糟糕。 It takes in degrees and returns radians, so it should probably be named operator"" _rads .它以度为单位并返回弧度,因此它可能应该被命名为operator"" _rads The purpose of UDLs is to have convenient, easy to read syntax, and a function that lies about what it does actively undermines that. UDL 的目的是提供方便、易于阅读的语法,以及一个 function 的谎言,它的所作所为积极破坏了这一点。


You can use this operator to do pretty much any computation you want (with constraints on the type, and number of the arguments passed in, similar to other operators), for example:您可以使用此运算符进行几乎任何您想要的计算(对传入的 arguments 的类型和数量进行限制,类似于其他运算符),例如:

constexpr long double operator"" _plus_one ( long double n )
{
    return n + 1;
}

Though the usage of this operator would still be the same as above.尽管此运算符的用法仍与上述相同。

Here's a demo .这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM