Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time replacement of string constants with integers

Tags:

c++

c++11

I have a list of pre-defined mappings of string constants to numbers outside of my code base. The integers map to data inside of the program but I want to use the far more readable string constants in my code. The resulting binary should only contain the numbers and not contain the string constants at all. Is it possible to replace the string constants with the mapped integer at compile time?

What I want to achieve is basically having this code:

getData("a string constant here");

and I want to transform it into this:

getData(277562452);

Is this possible via macros or constexpr?

like image 227
xen Avatar asked Dec 15 '22 05:12

xen


2 Answers

#define astrconst 277562452

Or

enum Strs { astrconst = 277562452 };
like image 112
Ivan Rubinson Avatar answered May 21 '23 10:05

Ivan Rubinson


You could use a custom suffix (see user-defined literals)

This would be used like this:

getData("a string constant here"_hash);

or simply use a consexpr hash function:

getData(hash("a string constant here"));

There is examples of constexpr hash functions out there

edit: If the mapping is already defined, my answer wont help much...

like image 43
johan d Avatar answered May 21 '23 10:05

johan d