Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 329
Jeremy Natale Avatar asked May 30 '26 20:05

Jeremy Natale


1 Answers

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.

like image 94
Angew is no longer proud of SO Avatar answered Jun 01 '26 08:06

Angew is no longer proud of SO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!