C++ compile time function execution
c++, template-meta-programming
Solution
You cannot operate on string literals at compile-time, so what you want isn't feasible in the way you suggested. However, if you're contemplating to process these strings at compile-time, then this means you know all strings at compile-time, and from that you might arrive at acceptable approximations to what you want.
The code you showed implies that the number generation (let's call it a hash) is invoked every time someone searches for a tag. Would reducing this to one invocation be acceptable? If so, you could define constants and use these instead of strings:
const int SomeTag = toNumber("SomeTag" );
const int SomeOtherTag = toNumber("SomeOtherTag" );
const int YetAnotherTag = toNumber("YetAnotherTag");
// ...
Then, simply replace all occurances of `search("SomeTag")` by `search(SomeTag)`.
If there's a great number of tags, typing the above could be very tedious, in which case a macro might help:
#define DEFINE_TAG(Tag_) const int Tag_ = toNumber(#Tag_);
DEFINE_TAG(SomeTag);
DEFINE_TAG(SomeOtherTag);
DEFINE_TAG(YetAnotherTag);
// ...
#undef DEFINE_TAG
Problem
I have string tags in my code that are converted to numbers and used to search values in a tag-value structure. I have something like this: ``` void foo() { type value = search("SomeTag"); } ``` Where search is defined like this: ``` type search(const char* tag) { return internal_search(toNumber(tag)); } ``` Because all the time tag is constant at compile time I want to remove the call that converts the tag to a number from search function. I know it is possible to execute some simple functions at compile time using templates (http://en.wikipedia.org/wiki/Compile_time_function_execution), but I don't know exactly how to iterate through a null terminated string and keep intermediate values in the template. Can you give a simple sample that iterates a null terminated string and adds the chars in a public variable please?