简体   繁体   English

std :: hash for std :: chrono :: duration

[英]std::hash for std::chrono::duration

I'm trying to key a set of objects on a std::chrono::duration. 我正在尝试在std :: chrono :: duration上键入一组对象。 This will not compile: 这不会编译:

#include <unordered_map>
#include <chrono>

class Foo final
{
public:

    Foo() {}

    int y;
};


int main(void)
{
    auto map = std::unordered_map<std::chrono::duration<int, std::milli>, Foo>();

    map[std::chrono::duration<int, std::milli>(5)].y = 0;

    return 0;
}

/usr/include/c++/4.9/bits/hashtable_policy.h: In instantiation of 'struct std::__detail::__is_noexcept_hash >, std::hash > > >': /usr/include/c++/4.9/bits/hashtable_policy.h:在'struct std :: __ detail :: __ is_noexcept_hash>,std :: hash >> >>'的实例化中:

I'm guessing the problem here is there's no std::hash implementation for std::chrono::duration? 我猜这里的问题是std :: chrono :: duration没有std :: hash实现吗? If not, is there a way of doing this without resorting to keying on the eminently breakable count()? 如果没有,有没有一种方法可以做到这一点,而不是诉诸于显着易碎的计数()?

Well, you could hide count under your own std::hash implementation http://en.cppreference.com/w/cpp/utility/hash : 好吧,你可以在自己的std :: hash实现中隐藏counthttp//en.cppreference.com/w/cpp/utility/hash

#include <unordered_map>
#include <chrono>

class Foo final
{
public:

    Foo() {}

    int y;
};

using namespace std::chrono_literals;

// custom specialization of std::hash can be injected in namespace std
namespace std
{
    template<typename _rep, typename ratio>
    struct hash<std::chrono::duration<_rep, ratio>>
    {
        typedef std::chrono::duration<_rep, ratio> argument_type;
        typedef std::size_t result_type;
        result_type operator()(argument_type const& s) const
        {
            return std::hash<_rep>{}(s.count());
        }
    };
}


int main(void)
{
    auto map = std::unordered_map<std::chrono::duration<float, std::milli>, Foo>();

    map[std::chrono::duration<float, std::milli>(5)].y = 12;
    std::cout << map[5ms].y; // thanks to std::chrono_literals

    return 0;
}

If you are afraid of passing different ratios into your map you could also use static_cast into some minimal time precision, eg. 如果您害怕将不同的比率传递到地图中,您还可以将static_cast用于一些最小的时间精度,例如。 std::micro : std::micro

return std::hash<_rep>{}( static_cast<std::chrono::duration<_rep, std::micro>>(s).count()); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM