Zhi*_*har 3 c++ time user-defined-literals c++11 c++14
告诉我,C ++ 11/14/17 中是否存在以下内容:
1)使用时间后缀设置时间
double time1 = 1s; // time1 = 1.0
double time2 = 2m; // time2 = 120.0
double time3 = 7ms; // time3 = 0.007
Run Code Online (Sandbox Code Playgroud)
2)获取设置后缀的时间字符串值
std::cout << getTime(time1); // cout 1s
std::cout << getTime(time2); // cout 2s
std::cout << getTime(time3); // cout 7ms
Run Code Online (Sandbox Code Playgroud)
是的,通过std::chrono_literals。
不直接,但您可以打印typeid(可用于调试)或自己提供流持续时间的重载。
我在这里包含了显式重载operator<<,但作为@JeJo,它也可以使用模板来完成: https: //wandbox.org/permlink/o495eXlv4rQ3z6yP
#include <iostream>
#include <chrono>
#include <typeinfo>
using namespace std::chrono_literals;
// example overloads for streaming out durations
std::ostream& operator<<(std::ostream& os, const std::chrono::nanoseconds& v) {
return os << v.count() << "ns";
}
std::ostream& operator<<(std::ostream& os, const std::chrono::microseconds& v) {
return os << v.count() << "us";
}
std::ostream& operator<<(std::ostream& os, const std::chrono::milliseconds& v) {
return os << v.count() << "ms";
}
std::ostream& operator<<(std::ostream& os, const std::chrono::seconds& v) {
return os << v.count() << "s";
}
std::ostream& operator<<(std::ostream& os, const std::chrono::minutes& v) {
return os << v.count() << "min";
}
std::ostream& operator<<(std::ostream& os, const std::chrono::hours& v) {
return os << v.count() << "h";
}
int main() {
auto time1 = 1s;
auto time2 = 2min;
auto time3 = 7ms;
std::cout << time1.count() << " " << typeid(time1).name() << "\n";
std::cout << time2.count() << " " << typeid(time2).name() << "\n";
std::cout << time3.count() << " " << typeid(time3).name() << "\n";
std::cout << time1 << "\n";
std::cout << time2 << "\n";
std::cout << time3 << "\n";
}
Run Code Online (Sandbox Code Playgroud)
可能的输出:
1 NSt6chrono8durationIlSt5ratioILl1ELl1EEEE
2 NSt6chrono8durationIlSt5ratioILl60ELl1EEEE
7 NSt6chrono8durationIlSt5ratioILl1ELl1000EEEE
1s
2min
7ms
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3168 次 |
| 最近记录: |