Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is s in std::this_thread::sleep_for(2s)?

Tags:

c++

c++14

I find the std::this_thread::sleep_for can process the time unit s.

std::this_thread::sleep_for(2s);

But I don't know what the s in 2s is.

like image 812
Zhang Avatar asked Nov 15 '18 09:11

Zhang


1 Answers

What is s in std::this_thread::sleep_for(2s)?

s is a user-defined literal making 2s a literal value of type chrono::second.


Built-in literals

You might be familiar with integer literals and floating literals; those are built-in suffixes:

+--------+---------+---------------+
| Suffix | Example |     Type      |
+--------+---------+---------------+
|      U |     42U | unsigned int  |
|     LL |     1LL | long long int |
|      f |   3.14f | float         |
+--------+---------+---------------+

They let you provide a literal value whose type matches your needs. For example:

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)

User-defined literals

C++11 added a new feature: user-defined literal suffixes:

Allows integer, floating-point, character, and string literals to produce objects of user-defined type by defining a user-defined suffix.

Syntax

They allow to provide a literal of a user-defined type or a Standard Library-defined type. Defining a literal is as easy as defining the operator"":

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

Example

#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';
}

Outputs "6.62874 kg" (demo) as it should.

The case of std::chrono

Unlike "real" user-provided literals, the Standard Library provides literals not starting with an underscore (_). s is one of them and is defined in <chrono> (since C++14):

constexpr chrono::seconds operator "" s(unsigned long long secs);

With other duration literals, it let you write something as pretty as:

#include <chrono>
using namespace std::chrono_literals;
const auto world_marathon_record_2018 = 2h + 1min + 39s;
like image 90
YSC Avatar answered Nov 15 '22 22:11

YSC