在C ++ 17/C ++ 2a中的编译时散列类型 [英] Hashing types at compile-time in C++17/C++2a
问题描述
考虑以下代码:
#include <iostream>
#include <type_traits>
template <class T>
constexpr std::size_t type_hash(T) noexcept
{
// Compute a hash for the type
// DO SOMETHING SMART HERE
}
int main(int argc, char* argv[])
{
auto x = []{};
auto y = []{};
auto z = x;
std::cout << std::is_same_v<decltype(x), decltype(y)> << std::endl; // 0
std::cout << std::is_same_v<decltype(x), decltype(z)> << std::endl; // 1
constexpr std::size_t xhash = type_hash(x);
constexpr std::size_t yhash = type_hash(y);
constexpr std::size_t zhash = type_hash(z);
std::cout << (xhash == yhash) << std::endl; // should be 0
std::cout << (yhash == zhash) << std::endl; // should be 1
return 0;
}
我希望type_hash
函数在编译时返回该类型唯一的哈希键.是否可以在C ++ 17或C ++ 2a中做到这一点(理想情况下仅依赖于标准,而无需依赖编译器内部函数)?
I would like the type_hash
function to return a hash key unique to the type, at compile-time. Is there a way to do that in C++17, or in C++2a (ideally only relying on the standard and without relying compiler intrinsics)?
推荐答案
我不知道一种为哈希获取std::size_t
的方法.
I don't know a way to obtain a std::size_t
for the hash.
但是,如果您接受指向某个东西的指针,也许可以在模板类中获取静态成员的地址.
But if you accept a pointer to something, maybe you can take the address of a static member in a template class.
我的意思是……如下
#include <iostream>
#include <type_traits>
template <typename>
struct type_hash
{
static constexpr int i { };
static constexpr int const * value { &i };
};
template <typename T>
static constexpr auto type_hash_v = type_hash<T>::value;
int main ()
{
auto x = []{};
auto y = []{};
auto z = x;
std::cout << std::is_same_v<decltype(x), decltype(y)> << std::endl; // 0
std::cout << std::is_same_v<decltype(x), decltype(z)> << std::endl; // 1
constexpr auto xhash = type_hash_v<decltype(x)>;
constexpr auto yhash = type_hash_v<decltype(y)>;
constexpr auto zhash = type_hash_v<decltype(z)>;
std::cout << (xhash == yhash) << std::endl; // should be 0
std::cout << (xhash == zhash) << std::endl; // should be 1
} // ...........^^^^^ xhash, not yhash
如果您真的想将type_hash
作为函数,我想您可以简单地创建一个返回所接收类型的type_hash_v<T>
的函数.
If you really want type_hash
as a function, I suppose you could simply create a function that return the type_hash_v<T>
of the type received.
这篇关于在C ++ 17/C ++ 2a中的编译时散列类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!