1

我正在实现一个简单的配置文件功能:

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是否有任何可能的策略来解决这个问题?

4

1 回答 1

2

好的,我得到了答案:

#include <type_traits>

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

将工作。

于 2013-07-02T16:29:39.057 回答