c++ - 缩短 C++ 模板函数名称

标签 c++ c++11

我知道,要缩短类名,我可以执行以下操作:

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/

相关文章:

c++ - 如何将 C++ 字符串转换为大写

c++ - 在 thrift 上确定服务器功能

c++ - Qt 获取不同操作系统的默认样式表

c++ - i +=++i 在 C++0x 中是未定义的行为吗?

c++ - 在 C++ 中将变量作为二维数组的维度问题

c++ - 在编译时获取变量名的标准方法

c++ - 如何防止另一个线程修改状态标志?

c++ - 我的 2D 迷宫解算器无限递归并且出现堆栈溢出 - 为什么?

c++ - bool 自动转换为 nullptr_t

c++ - 在 C++ 中将多个参数绑定(bind)到成员函数