什么是std :: this_thread :: sleep_for(2s)中的s?

Zha*_*ang 5 c++ c++14

我发现std :: this_thread :: sleep_for可以处理时间单位s.

std::this_thread::sleep_for(2s);
Run Code Online (Sandbox Code Playgroud)

但我不知道是什么s2s是.

YSC*_*YSC 12

什么sstd::this_thread::sleep_for(2s)

s用户定义的文字,使2s文字值为type chrono::second.


内置文字

您可能熟悉整数文字浮动文字 ; 那些是内置后缀:

+--------+---------+---------------+
| Suffix | Example |     Type      |
+--------+---------+---------------+
|      U |     42U | unsigned int  |
|     LL |     1LL | long long int |
|      f |   3.14f | float         |
+--------+---------+---------------+
Run Code Online (Sandbox Code Playgroud)

它们允许您提供类型符合您需求的文字值.例如:

int   half(int n)   { return n/2; }
float half(float f) { return f/2; }
half(3);   // calls the int   version, returns 1    (int)
half(3.f); // calls the float version, returns 1.5f (float)
Run Code Online (Sandbox Code Playgroud)

用户定义的文字

C++ 11添加了一个新功能:用户定义的文字后缀:

允许整数,浮点,字符和字符串文字通过定义用户定义的后缀来生成用户定义类型的对象.

句法

它们允许提供用户定义类型或标准库定义类型的文字.定义文字就像定义operator"":

// 0_<suffix> is now a <type> literal
<type> operator "" _<suffix>(unsigned long long); // ull: one of the height existing forms
Run Code Online (Sandbox Code Playgroud)

#include <iostream>

class Mass
{
    double _value_in_kg;
public:
    Mass(long double kg) : _value_in_kg(kg) {}
    friend Mass          operator+ (Mass const& m1, Mass const& m2)  { return m1._value_in_kg + m2._value_in_kg; }
    friend std::ostream& operator<<(std::ostream& os, Mass const& m) { return os << m._value_in_kg << " kg"; }
};

Mass operator "" _kg(long double kg) { return Mass{kg}; }
Mass operator "" _lb(long double lb) { return Mass{lb/2.20462}; }

int main()
{
    std::cout << 3.0_kg + 8.0_lb  << '\n';
}
Run Code Online (Sandbox Code Playgroud)

输出"6.62874千克"(演示)作为它应该.

的情况下 std::chrono

与"真实的"用户提供的文字不同,标准库提供的文字不是以下划线(_)开头的.s是其中之一,并在<chrono>(自C++ 14)中定义:

constexpr chrono::seconds operator "" s(unsigned long long secs);
Run Code Online (Sandbox Code Playgroud)

使用其他持续时间文字,它可以让你写一些漂亮的东西:

#include <chrono>
using namespace std::chrono_literals;
const auto world_marathon_record_2018 = 2h + 1min + 39s;
Run Code Online (Sandbox Code Playgroud)