【C++奇技淫巧】std::literals是什么以及怎么用【2023.02.04】

📙前言

学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小时…

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值