2013-07-02 29 views
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的構造函數時,函數對象被傳遞。有沒有可能的策略來解決這個問題?

+1

'decltype(func())'會做,順便說一句。 –

+0

@Fernades好點,我沒有注意到這一點。 – xis

回答

2

OK,我得到了答案:

#include <type_traits> 

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

會工作。

相關問題