c++ - 尝试将任何函数作为参数发送并推断类型?

标签 c++

我想将一个函数作为参数传递给执行该函数的包装函数,计算执行时间并打印它,然后返回该函数的返回值。这是我到目前为止尝试做的。

#include  <functional>
#include <chrono>

namespace TimeIt {

template <typename T>
auto time_it(std::string name, std::function<T> work) -> decltype(work()) {
    auto start = std::chrono::high_resolution_clock::now();
    auto return_value = work();
    auto stop = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    printf("Time taken by function:%s is %lld",name, duration.count());

    return return_value;
}
}

最佳答案

在这里尝试将所有内容包装在 std::function 中是非常有害的,您应该只推导原始的可调用类型。

template <typename Callable, typename ... Args>
auto time_it(std::string name, Callable&& work, Args&&... args) -> std::invoke_result_t<Callable, Args...> {
    auto start = std::chrono::high_resolution_clock::now();
    auto return_value = std::invoke(std::forward<Callable>(work), std::forward<Args>(args)...);
    auto stop = std::chrono::high_resolution_clock::now();

    auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start);
    printf("Time taken by function:%s is %lld",name, duration.count());

    return return_value;
}

关于c++ - 尝试将任何函数作为参数发送并推断类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229335/

相关文章:

c++ - 从指针删除到指针 vector

c++ - 在 Windows 10 上使用 vcpkg 安装 Dear ImGui

java - 如何在 JNI 中访问从 C++ 返回 java.lang.String 的 Java 方法的返回值?

c++ - 使用 `getline(cin, s);` 后使用 `cin >> n;`

c++ - 何时以及如何在 C++ 中初始化静态数据?

c++ - 为什么虚函数会被隐藏?

c++ - 投影网格水位线细节

c++ - C/++函数如何正确返回值?

c++ - 欧几里得算法函数参数

c++ - 如何将 boost::filesystem::directory_entry::path() 值分配给字符串?