在命名空间 std 之外专门化 std::hash 是否不安全?

问题描述

我知道我们只能向 namespace std 添加代码,它是在那里定义的模板的模板特化,否则行为未定义。

我已经从 C++ 入门中实现了这段代码:

//namespace std
//{
    template <>
    class std::hash<Sales_data>
//   class hash<Sales_data>
    {
    public:
        using result_type = std::size_t;
        using argument_type = Sales_data;
        result_type operator()(argument_type const& ) const;
    };

    typename hash<Sales_data>::result_type
    hash<Sales_data>::operator()(argument_type const& arg) const
    {
        return hash<std::string>()(arg.isbn_) ^
                hash<unsigned int>()(arg.nCopySold_) ^
                hash<double>()(arg.revenue_);
    }
//}
  • 代码工作正常,所以我是将代码注入到命名空间 std: template <> class std::hash<Sales_data> 还是只是我在命名空间之外专门化了 std::hash ?原始代码使用的是未注释的行。

  • 我不应该这样做还是这样做是错误的?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)