我正在实现一个简单的配置文件函数:
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/