📙前言
学c++20标准里面的信号量的时候遇到了std::literals
,一时懵逼。实际上很简单,literals翻译过来就是字面量。比如有个参数是3毫秒,我们可以直接写成3ms,编译器自动把3ms转成对应的类型。比如3小时,我们可以写成3h,编译器自动转换成函数参数对应的类型。看完下面的例子就懂了。
💡例子
C++11标准里有个计时类chrono
,让当前线程sleep六秒钟的用法如下。
#include <iostream>
#include <sstream>
#include <time.h>
#include <chrono>
#include <ratio>
#include <thread>
/// <summary>
/// 打印当前时间
/// </summary>
void printCurrentTime()
{
time_t now = time(NULL);
tm tm_t;
int ret = localtime_s(&tm_t, &now);
std::stringstream ss;
ss << tm_t.tm_hour << ":" << tm_t.tm_min << ":" << tm_t.tm_sec << std::endl;
std::cout << ss.str();
}
int main()
{
// duration 翻译是一段时间一段时间一段
// 定义计时器要用到的秒类型
typedef std::chrono::duration<int> seconds_type;//[注释:duration的类型定义]
seconds_type seconds_6(6);//6秒
printCurrentTime();
std::this_thread::sleep_for(seconds_6);//sleep 6秒钟
printCurrentTime();
}
阅读代码得知,如果用到chrono
则难以避免要用到duration类型,而duration类型的定义又比较复杂。所以std::literals
就出来了,还是直接看例子。
// testChrono.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <sstream>
#include <time.h>
#include <chrono>
#include <ratio>
#include <thread>
/// <summary>
/// 打印当前时间
/// </summary>
void printCurrentTime()
{
time_t now = time(NULL);
tm tm_t;
int ret = localtime_s(&tm_t, &now);
std::stringstream ss;
ss << tm_t.tm_hour << ":" << tm_t.tm_min << ":" << tm_t.tm_sec << std::endl;
std::cout << ss.str();
}
int main()
{
using namespace std::literals;
printCurrentTime();
std::this_thread::sleep_for(3s);//sleep 三秒
printCurrentTime();
}
💗总结
使用了using namespace std::literals;
之后,我们可以3s直接表示3秒、3ms表示3毫秒、3h表示3小时…