c++ - 获取回调函数的返回类型

标签 c++ c++11 bind decltype

我正在实现一个简单的配置文件函数:

template <typename T>
typename T::return_type ProfilerRun(T&& func, const std::string& routine_name = "unknown" )
{
    using std::chrono::duration_cast;
    using std::chrono::microseconds;
    using std::chrono::steady_clock;
    using std::cerr;
    using std::endl;
#ifdef SELF_PROFILING
    steady_clock::time_point t_begin = steady_clock::now();
#endif
    func();
#ifdef SELF_PROFILING
    steady_clock::time_point t_end = steady_clock::now();
    cerr << "Function " << routine_name << " duration: " <<
         duration_cast<microseconds>( t_end - t_begin ).count() <<
         " microseconds." << endl;
#endif
}

这与 std::bind(&Class::function, class_object, param1, param2, ...) 完美配合,但它不适用于原始函数指针,因为它们没有T::result_type 属性。我也想过

auto ProfilerRun(T&& func, const std::string&) -> decltype(T()))

但在这种情况下,decltype 将在传递函数对象时调用 T 的构造函数。有什么可能的策略来解决这个问题吗?

最佳答案

好的,我得到了答案:

#include <type_traits>

typename std::result_of<T()>::type ProfilerRun(T&&, const std::string&);

会起作用。

关于c++ - 获取回调函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17430817/

相关文章:

c++ - 如何让输入文件读入 C++ 中的字符串数组?

c++ - 任意但编译时已知数量的类型的元组

c++ - 在派生模板类中使用条件类型特征覆盖基类中的虚拟方法

c++ - 为什么 std::shared_ptr 没有 [] 运算符?

c++ - boost::bind 为具有默认值的成员函数?

c++ 可以将字符串值转换为类型吗?

c++ - future::wait() 是否与 async() 执行线程的完成同步?

c# - 如何以编程方式清除 Kerberos 票证缓存

javascript - 对每个表行 react onclick

c++ - 绑定(bind)通用成员函数