vimwiki/lang/constexpr.wiki
2021-09-22 13:23:25 -04:00

34 lines
975 B
Plaintext

= 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){
return *input ?
static_cast<unsigned_int>(*input) + 33 * const_hash(input + 1) :
5381;
}
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++]]