gpt4 book ai didi

c++ - 为什么 std::hash 不专用于 char*?

转载 作者:可可西里 更新时间:2023-11-01 15:39:30 27 4
gpt4 key购买 nike

为什么 C++ 标准不指定 std::hash<T>专门用于 char* , const char* , unsigned char* , const unsigned char* , ETC?即,它将散列 C 字符串的内容,直到找到终止 null。

将我自己的特化注入(inject) std 的任何危害我自己的代码的命名空间?

最佳答案

Why doesn't the C++ standard specify that std::hash<T> is specialized for char*, const char*, unsigned char*, const unsigned char*, etc?

看起来它起源于 proposal N1456 。 (强调我的)

Some earlier hash table implementations gave char* special treatment: it specialized the default hash function to look at character array being pointed to, rather than the pointer itself. This proposal removes that special treatment. Special treatment makes it slightly easier to use hash tables for C string, but at the cost of removing uniformity and making it harder to write generic code. Since naive users would generally be expected to use std::basic_string instead of C strings, the cost of special treatment outweighs the benefit.

如果我对此的解释正确,原因是支持 C 风格的字符串会破坏通常作用于指针散列的代码。

Any harm in injecting my own specializations into the std namespace for my own code?

有潜在危害,是的。

  • 将来,您添加到 std 命名空间的任何内容都可能与新的符号名称发生冲突。
  • 目前,您添加到 std 命名空间的任何内容都可以“更好地匹配”标准库的其他组件,无声地破坏行为。

关于c++ - 为什么 std::hash<T> 不专用于 char*?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16044551/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com