vimwiki/tech/constexpr.wiki

34 lines
970 B
Plaintext
Raw Normal View History

2021-09-22 17:23:25 +00:00
= Constexpr =
Constexpr is this great C++11 feature that marks a value or function to be
known/executed at compile time. This is great for things likes config.hpp
files, compile time string hashes, and more.
== Example ==
{{{C++
unsigned int constexpr const_hash(char const *str){
2022-02-01 02:07:42 +00:00
return *input ?
2021-09-22 17:23:25 +00:00
static_cast<unsigned_int>(*input) + 33 * const_hash(input + 1) :
5381;
}
2022-02-01 02:07:42 +00:00
2021-09-22 17:23:25 +00:00
void main(){
constexpr char* const_str = "12345";
switch(const_hash(const_str)){
case const_hash("12345"):
std::cout << "Found 12345\n";
break;
case const_hash("54321"):
std::cout << "Found 54321\n";
break;
}
}
}}}
Switch statements can only accept integers in C/C++, however using this we can
convert compile time strings into integers. This is wonderful for making code
more readable, without relying to much on C macros, which are not type aware.
[[C++]]