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

Jer*_*ale 3 c++ linux stdthread gcc4.8 stdhash

我正在努力获得一个C++应用程序,以便在Windows和Linux中进行编译,在我发现的一些调试过程中

std::this_thread::get_id().hash()
Run Code Online (Sandbox Code Playgroud)

不能在Linux上用gcc 4.8编译(感谢这个帖子中的注释).建议的解决方法是使用:

std::hash<std::thread::id>()(std::this_thread::get_id())
Run Code Online (Sandbox Code Playgroud)

有谁知道这些是否产生相同的输出?

Rei*_*ica 5

GCC拒绝代码是正确的.该标准没有定义一个成员hashstd::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>;
}
Run Code Online (Sandbox Code Playgroud)

因此,使用std::hash<std::thread::id>()(std::this_thread::get_id())肯定是获取线程ID哈希的有效(实际上唯一有效)方式.