我只是在这里将我的答案作为一大块代码倾倒,因为我担心我对模板参数推导没有很好的解释。
我认为这与std::chrono::system_clock::time_point
成为typedef
for 有关std::chrono::time_point<std::chrono::system_clock>
,但我不确定,我希望有人能给出一个很好的解释。在那之前,我只是在倾倒 2 个可行的解决方案。
#include <chrono>
#include <string>
#include <sstream>
#include <iostream>
template< class CLOCK >
std::string print_date_time( typename CLOCK::time_point p_time ){
std::stringstream ss;
std::time_t t = CLOCK::to_time_t(p_time);
ss << std::ctime(&t) << std::endl;
return ss.str();
}
// You can do this
template< class CLOCK >
std::string print_date_time_2( typename std::chrono::time_point<CLOCK> p_time ){
std::stringstream ss;
std::time_t t = CLOCK::to_time_t(p_time);
ss << std::ctime(&t) << std::endl;
return ss.str();
}
// Or this
template< class TIME_POINT >
std::string print_date_time_3( TIME_POINT p_time ){
std::stringstream ss;
std::time_t t = TIME_POINT::clock::to_time_t(p_time);
ss << std::ctime(&t) << std::endl;
return ss.str();
}
int main()
{
std::cout
<< print_date_time
<std::chrono::system_clock> // You don't want this!!
// But without it you get template
// argument deduction errors.
(std::chrono::system_clock::now())
<< '\n';
std::cout
<< print_date_time_2
(std::chrono::system_clock::now())
<< '\n';
std::cout
<< print_date_time_3
(std::chrono::system_clock::now())
<< '\n';
}