Search code examples
c++linuxstdthreadgcc4.8stdhash

Using std::hash<std::thread::id>()(std::this_thread::get_id())


I'm currently working on getting a C++ application to compile in both Windows and Linux, during some debugging I've found that

std::this_thread::get_id().hash()

doesn't compile on Linux with gcc 4.8 (thanks to the comments in this thread). The suggested fix for this was to use:

std::hash<std::thread::id>()(std::this_thread::get_id())

Does anyone know if these produce the same output?


Solution

  • GCC is right to reject the code. The standard does not define a member hash for std::thread::id. C++11, 30.3.1.1:

    namespace std {
      class thread::id {
      public:
        id() noexcept;
      };
    
      bool operator==(thread::id x, thread::id y) noexcept;
      bool operator!=(thread::id x, thread::id y) noexcept;
      bool operator<(thread::id x, thread::id y) noexcept;
      bool operator<=(thread::id x, thread::id y) noexcept;
      bool operator>(thread::id x, thread::id y) noexcept;
      bool operator>=(thread::id x, thread::id y) noexcept;
    
      template<class charT, class traits>
        basic_ostream<charT, traits>&
          operator<< (basic_ostream<charT, traits>& out, thread::id id);
    
      // Hash support
      template <class T> struct hash;
      template <> struct hash<thread::id>;
    }
    

    So using std::hash<std::thread::id>()(std::this_thread::get_id()) is certainly a valid (actually the only valid) way of getting a hash of a thread ID.