Example
#include <cmath>
constexpr auto positive = std::abs(-2);
static_assert(positive == 2);
Puzzle
- Can you implement
number
user defined literal (UDL) which uses constexpr functions?
#include <cmath>
template <char... Cs>
[[nodiscard]] constexpr auto operator""_number(); // TODO
static_assert(0 == 0_number);
static_assert(42 == 42_number);
static_assert(123 == 123_number);
Solutions
template <char... Cs>
[[nodiscard]] constexpr auto operator""_number() {
return []<auto... Is, class T = int>(std::index_sequence<Is...>) {
return std::integral_constant<
T, (((Cs - '0') * T(std::pow(T(10), sizeof...(Is) - Is - 1))) +
...)>{};
}
(std::make_index_sequence<sizeof...(Cs)>{});
}
template <char... Cs>
[[nodiscard]] constexpr auto operator""_number() {
int result = 0;
((result = result * 10 + (Cs - '0')), ...);
return result;
}