Use cases for consteval

While we could use constexpr before consteval, sometimes in complex code one of the parameters could accidently or otherwise omit the const/constexpr qualifier. This would cause functions we expect to be evaluated at compile time to be evaluated at run time. The consteval keyword forces a fix on this, but also has the following use cases:

1. Check that your constexpr values are within expected ranges during compiletime

consteval int check_valid(int n) {
	if(n > kMaxValue) {
		throw std::logic_error("Value exceeds maximum.");
	}
	return n;
}

2. Get compile-time info about a class, such as it’s size (eg for serialization).

template <typename T>
consteval std::size_t getTypeSize() {
		return sizeof(T);
}

3. You can build complex strings in a consteval function, which will be evaluated at compiletime.

4. Ensure that complex derivatives are consteval, thus a complicated function becomes a single number after compilation, and now you don’t have to pay attention that every single parameter truly is constexpr. This saves a bit of pain.

Leave a Reply

Your email address will not be published. Required fields are marked *