std::type_info::hash_code(3)
π std::type_info::hash_code(3) π
okay so this is the std::type_info::hash_code page from the C++ Standard Libary manual, and we're gonna make it make sense bestie π
β¨
π NAME π
std::type_info::hash_code β std::type_info::hash_code. yes, it's literally the same name twice, no thoughts, just iconic π
β¨ Synopsis β¨
std::size_t hash_code() const noexcept; (since C++11)
Returns an unspecified value (here denoted by hash code) such that for all std::type_info objects referring to the same type, their hash code is the same. fr fr πΈ
No other guarantees are given: std::type_info objects referring to different types may have the same hash code (although the standard recommends that implementations avoid this as much as possible), and hash code for the same type can change between invocations of the same program. π
π«Ά Parameters π«Ά
(none) β literally none, bestie π
π Return value π
A value that is identical for all std::type_info objects referring to the same type. iykyk β¨
π₯ Example π₯
The following program is an example of an efficient type-value mapping without using std::type_index. periodt. π
The page says // Run this code β run it, it's giving main character energy πββοΈπ¨
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <typeinfo>
#include <unordered_map>
struct A
{
virtual ~A() {}
};
struct B : A {};
struct C : A {};
using TypeInfoRef = std::reference_wrapper<const std::type_info>;
struct Hasher
{
std::size_t operator()(TypeInfoRef code) const
{
return code.get().hash_code();
}
};
struct EqualTo
{
bool operator()(TypeInfoRef lhs, TypeInfoRef rhs) const
{
return lhs.get() == rhs.get();
}
};
int main()
{
std::unordered_map<TypeInfoRef, std::string, Hasher, EqualTo>
type_names;
type_names[typeid(int)] = "int";
type_names[typeid(double)] = "double";
type_names[typeid(A)] = "A";
type_names[typeid(B)] = "B";
type_names[typeid(C)] = "C";
int i;
double d;
A a;
// note that we're storing pointer to type A
std::unique_ptr<A> b(new B);
std::unique_ptr<A> c(new C);
std::cout << "i is " << type_names[typeid(i)] << '\n';
std::cout << "d is " << type_names[typeid(d)] << '\n';
std::cout << "a is " << type_names[typeid(a)] << '\n';
std::cout << "*b is " << type_names[typeid(*b)] << '\n';
std::cout << "*c is " << type_names[typeid(*c)] << '\n';
}
Output:
i is int
d is double
a is A
*b is B
*c is C
π See also π
operator==β checks whether the objects refer to the same typeoperator!=β (public member function) (removed in C++20)nameβ implementation defined name of the type (public member function)
kisses from http://cppreference.com π version/date 2024.06.10, page std::type_info::hash_code(3) β bye bestie, go slay your type maps ππ«Ά
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms