我正在实现一个简单的配置文件功能:
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
是否有任何可能的策略来解决这个问题?