缩短C++模板函数名称

Bha*_*rag 1 c++ c++11

我知道,为了缩短课程名称,我可以做以下事情:

using Time = std::chrono::time_point<std::chrono::system_clock>;
using Clock = std::chrono::system_clock;
Run Code Online (Sandbox Code Playgroud)

但如何正确减少下一行的长度?

/*using Ms = */ std::chrono::duration_cast<std::chrono::milliseconds>
Run Code Online (Sandbox Code Playgroud)

目标代码:

Time start = Clock::now();
// something
Time end = Clock::now();
std::cout << Ms(end - start).count() << std::endl;
Run Code Online (Sandbox Code Playgroud)

Jus*_*tin 7

你有几个选择.您可以使用using声明:

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;
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以编写自己的函数:

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;
}
Run Code Online (Sandbox Code Playgroud)