在 C++11 中调用模板参数的函数,其中模板参数为 chrono::system_clock
calling a function of template parameter in c++11 where template parameter is chrono::system_clock
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
成为std::chrono::time_point<std::chrono::system_clock>
的typedef
有关,但我不确定,我希望有人能给出一个很好的解释。在那之前,我只是倾倒 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';
}
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;
}
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 如何使用默认参数等选择模板专业化
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 从持续时间构造std::chrono::system_clock::time_point
- 函数调用中参数的顺序重要吗
- 部分定义/别名模板模板参数
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 使用不带参数的函数访问结构元素
- 基于另一个成员参数将函数调用从类传递给它的一个成员
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 如何使用Luacneneneba API正确读取字符串和表参数
- 在派生函数中指定void*参数
- 视图中的参数推导失败:take_while
- 如何正确地将 boost::optional<std::chrono::d uration> 作为函数参数?
- 在模板具有3时,如何在std :: chrono :: duraction_cast中仅提供一种类型的参数
- 在 C++11 中调用模板参数的函数,其中模板参数为 chrono::system_clock