4 ms·
constexpr is much more powerful than just generating constants (although that is one of the bigger use cases). One of the things I like is how it simplifies doi
by clappski 7y ago
constexpr is much more powerful than just generating constants (although that is one of the bigger use cases). One of the things I like is how it simplifies doing static dispatch on template types, essentially using SFINAE under the hood but in a much simpler way to read:
if constexpr ( std::is_same_v<T, int> ) { ... }
Vs
template <typename T, typename std::enable_if_t<...>* = 0>
void fn( T t ) { }
Being able to generate constants using the language itself is super powerful as well (the below is a bit contrived, as std::string_view is constexpr and obsoletes this pattern):
static constexpr std::array<char[], SIZE> strs = { ... };
static constexpr std::array<size_t, SIZE> str_lens = calc( strs );
// Where calc() loops over the array and calls std::strlen, all at compile time