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();
}
int main(){
std::cout << print_date_time( std::chrono::system_clock::now() );
}
我确实提供了适当的文件,让我知道哪里出了问题。
我只是将答案作为一大堆代码转储在这里,因为恐怕我对模板参数推导没有很好的解释。
我认为这是一起做的std::chrono::system_clock::time_point
是一typedef
对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';
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句