在 C++11 中调用模板参数的函数,其中模板参数为 chrono::system_clock

calling a function of template parameter in c++11 where template parameter is chrono::system_clock

本文关键字:参数 chrono clock system 函数 调用 C++11      更新时间:2023-10-16
     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; 
}