C ++ 11 chrono有哪些替代方案?

时间:2014-08-06 21:57:55

标签: c++ c++11 boost ctime

我正在运行以下代码,用于检查data_timestamp是否超过两周。如果它超过两周,则打印hello否则打印world

我是一名Java开发人员,最近开始使用C ++。通过互联网学到了一些东西,所以我在这个程序中使用它。我没有意识到并非所有代码都可以使用C ++ 11功能运行。

#include <ctime>
#include <chrono>
#include <iostream>

int main()
{

    uint64_t data_timestamp = 1406066507000; 

    const auto now = std::chrono::system_clock::now();
    auto twoWeeks = std::chrono::hours(24 * 14);
    auto lastTwoWeeks = now - twoWeeks;

    auto millis = std::chrono::duration_cast<std::chrono::milliseconds>(lastTwoWeeks.time_since_epoch()).count();

    std::cout << "Time stamp in milliseconds since UNIX epoch start: "<< millis << std::endl;

    if (data_timestamp < millis) { 
        std::cout << "Hello"; 
    } else { 
        std::cout << "World"; 
    }

    return 0;
}

目前上面的代码使用C ++ 11功能,但我使用上述两周时间戳代码逻辑的实际代码并不支持C ++ 11,所以我正在寻找各种替代方案。

我在这里可以使用哪些不需要C ++ 11的可移植性?我可以在这里使用<ctime>Boost.Chrono吗?

任何与上面代码完全相同但不使用C ++ 11功能的简单示例都会有很大的帮助。

更新: -

以下是我正在尝试的代码 -

#include <boost/chrono/chrono.hpp>
#include <iostream>

int main()
{
    uint64_t data_timestamp = 1406066507000; 

    const auto now = boost::chrono::system_clock::now();
    auto twoWeeks = boost::chrono::hours(24 * 14);
    auto lastTwoWeeks = now - twoWeeks;

    auto millis = boost::chrono::duration_cast<boost::chrono::milliseconds>(lastTwoWeeks.time_since_epoch()).count();

    std::cout << "Time stamp in milliseconds since UNIX epoch start: "<< millis << std::endl;

    if (data_timestamp < millis) { 
        std::cout << "Hello"; 
    } else { 
        std::cout << "World"; 
    }

    return 0;
}

我正在使用下面的make install -j4编译代码是我要回的例外 -

warning: âautoâ changes meaning in C++11; please remove it [-Wc++0x-compat]
error: ânowâ does not name a type
warning: âautoâ changes meaning in C++11; please remove it [-Wc++0x-compat]
error: âtwoWeeksâ does not name a type
warning: âautoâ changes meaning in C++11; please remove it [-Wc++0x-compat]
error: âlastTwoWeeksâ does not name a type
warning: âautoâ changes meaning in C++11; please remove it [-Wc++0x-compat]
error: âmillisâ does not name a type
error: âmillisâ was not declared in this scope

1 个答案:

答案 0 :(得分:6)

我建议boost::chrono,因为C ++ 11规范主要基于boost::date_time(阅读诸如this one之类的提案会显示有多少提升被用作{{{{ 1}})。正如Howard Hinnant评论的那样,std::chrono被复制自boost::chrono

只要您可以使用C ++ 11编译器(易于移植到std::chrono

,它也会让您更轻松。

一个简单的例子:

std::
相关问题