C++ compile time function execution

后端 未结 6 1660
醉酒成梦
醉酒成梦 2021-01-02 02:41

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(         


        
6条回答
  •  鱼传尺愫
    2021-01-02 03:31

    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
    

提交回复
热议问题