你可以使用其基类的 std::hash 进行类型哈希。

huangapple go评论52阅读模式
英文:

How can I hash a type using the std::hash of its base class?

问题

以下是翻译好的代码部分:

#include <unordered_set>
#include <string>

template <bool B>
struct C : std::string
{
    C(std::string s) : std::string(s) {}
};

namespace std {

    template <bool B>
    struct hash<C<B>>
    {
        std::size_t operator()(const C<B> &k) const {
            return std::hash<std::string>()(static_cast<std::string>(k));
        }
    };

} // namespace std

int main() {
    std::unordered_set<C<false>> s;
    std::string c = C<false>("a");
    s.insert(c);
    return 0;
}
英文:

I have a class template C&lt;B&gt; which inherits from std::string, and I want to make it hashable like a normal std::string. I have written the following code, and it compiles.

I wonder if it is the correct implementation. Since a cast from derived class to base class may truncate memory, I wonder if it will cost too much?

#include &lt;unordered_set&gt;
#include &lt;string&gt;

template &lt;bool B&gt;
struct C : std::string
{
    C(std::string s) : std::string(s) {}
};

namespace std {

    template &lt;bool B&gt;
    struct hash&lt;C&lt;B&gt;&gt;
    {
        std::size_t operator()(const C&lt;B&gt; &amp;k) const {
            return std::hash&lt;std::string&gt;()(static_cast&lt;std::string&gt;(k));
        }
    };

} // namespace std

int main() {
    std::unordered_set&lt;C&lt;false&gt;&gt; s;
    std::string c = C&lt;false&gt;(&quot;a&quot;);
    s.insert(c);
    return 0;
}

答案1

得分: 6

是的,这个实现会工作,但不需要static_cast<std::string>(k) - 并且会创建一个临时的std::string,你可能想避免这种情况。

如果你改为static_cast<const std::string&&>(k),它就不会创建临时的std::string。如果你只是这样做也一样:

std::size_t operator()(const C<B>& k) const {
    return std::hash<std::string>()(k);
}
英文:

Yes, the implementation will work, but static_cast&lt;std::string&gt;(k) is not needed - and will create a temporary std::string which you probably would like to avoid.

If you instead make it static_cast&lt;const std::string&amp;&gt;(k), it will not create a temporary std::string. Same thing if you simply do:

std::size_t operator()(const C&lt;B&gt;&amp; k) const {
    return std::hash&lt;std::string&gt;()(k);
}

huangapple
  • 本文由 发表于 2023年6月12日 21:20:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定