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() );
}
我确实包含了正确的文件,让我知道哪里出错了。
答案 0 :(得分:1)
我只是把我的答案作为一大块代码丢弃,因为我担心我对模板参数推断没有很好的解释。
我认为这与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';
}
答案 1 :(得分:0)
print_data_time()
功能没有任何问题。以下代码有效:
#include<sstream>
#include<iostream>
#include<chrono>
#include<ctime>
using namespace std;
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()
{
chrono::system_clock::time_point now = chrono::system_clock::now();
cout << print_date_time<chrono::system_clock>(now) << endl;
}