A A
A A

Reputation: 41

Compile Time unique hash for variables

is there any ways of making unique hashes for each variable in compile time.

C++ allows block scopes which can result in same named variables inside one function so i cannot just do:

#define MACRO(...) ConstevalHash(__PRETTY_FUNCTION__ #__VA_ARGS__)

int variable = 0;
printf("id %d \n", MACRO(variable)); 

in compiled file should look like:

printf("id %d \n", 345908340) // unique hash

I thought of trying to get static memory address of each variable using consteval tricks but im afraid that is not possible with current cpp.

EDIT:

This is solving issue with compile time counters.

Current solution has been just:

#define MACRO(...) __VA_ARGS__.CachedID // static constexpr int CachedID ;

Var<ID, int> Variable = 0; // Id creates unique id using counter
MACRO(variable);

This disallows usage of auto which is not very good solution for any api.

About block scopes

void Function()
{
{ int var = 0; MACRO(var); } 
{ int var = 0; MACRO(var); }
}

while(true)
{
Function();
}

Both of these hashes should be different but they should remain the exact same in every tick inside a loop that's why compile time coding is required.

Upvotes: 0

Views: 122

Answers (1)

viraltaco_
viraltaco_

Reputation: 1200

I came up with this:

 template <class T> struct var {
     using  hash_type = unsigned;
     using value_type = T;
     
     value_type value;
     const hash_type cached_id;

     constexpr var(const value_type the_value) noexcept 
      : value(the_value)
      , cached_id([]{ static hash_type k; return k++; }())
     {}

     constexpr operator auto() noexcept { return value; }
 };

 template <class T> var(T const&) -> var<T>;

Live on Compiler Explorer
No macros. Is this what you're looking for?

Upvotes: 0

Related Questions