c++ - Constexpr function in constexpr constructor initialiser list -


i initialise struct member hash of struct name.

constexpr uint32_t myhash(const char* const data) { //some code hash     return myhash; }  struct my_struct{     constexpr test() : id(myhash("my_struct"))     {     }     const uint32_t id;  } 

when have:

constexpr my_struct my_constexpr_struct; 

then hash computed @ compile time successfully. however, when have in main function

my_struct my_normal_struct; 

then call the

constexpr uint32_t myhash(const char* const data) 

function in code instead of initialising struct member compile time constant.

this incur significant performance penalty avoidable.

any thoughts or suggestions on how have compiler perform @ compile time? don't want do:

constexpr uint32_t my_struct_id = myhash("my_struct"); struct my_struct{     constexpr test() : id(my_struct_id)     {     }     const uint32_t id;  

thanks.

constexpr request, not requirement. such, if initialize object outside of constant expression context, through constexpr constructor, there no guarantee initialization done @ compile time.

if want guarantee compile-time evaluation, have call constexpr function in constant expression context. if explicit use of variable offends in way, force constexpr evaluation through use of template:

template<typename t, t t> struct repeat {   using value_type = t;   static constexpr t value = t;   constexpr t operator()() const noexcept {return t;} };  struct my_struct{     constexpr my_struct() : id(repeat<uint32_t, myhash("my_struct")>::value)     {     }     const uint32_t id;  }; 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -