我知道,要缩短类名,我可以执行以下操作:
using Time = std::chrono::time_point<std::chrono::system_clock>;
using Clock = std::chrono::system_clock;
但是如何适当减少下一行的长度呢?
/*using Ms = */ std::chrono::duration_cast<std::chrono::milliseconds>
目标代码:
Time start = Clock::now();
// something
Time end = Clock::now();
std::cout << Ms(end - start).count() << std::endl;
最佳答案
您有几个选择。你可以使用 using declaration :
void foo() {
// These can be scoped to the function so they don't bleed into your API
using std::chrono::duration_cast;
using std::chrono::milliseconds;
Time start = Clock::now();
// something
Time end = Clock::now();
std::cout << duration_cast<milliseconds>(end - start).count() << std::endl;
}
或者,您可以编写自己的函数:
template <typename Duration>
auto as_ms(Duration const& duration) {
return std::chrono::duration_cast<std::chrono::milliseconds>(duration);
}
void foo() {
Time start = Clock::now();
// something
Time end = Clock::now();
std::cout << as_ms(end - start).count() << std::endl;
}
关于c++ - 缩短 C++ 模板函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49262898/