[go: up one dir, main page]

Skip to content

Latest commit

 

History

History
64 lines (45 loc) · 1.4 KB

347.md

File metadata and controls

64 lines (45 loc) · 1.4 KB
Info

*** Did you know that C++26 added more constexpr for and ?

Example

#include <cmath>
constexpr auto positive = std::abs(-2);
static_assert(positive == 2);

https://godbolt.org/z/ar1drdohP

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);

https://godbolt.org/z/8r4frajnv

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)>{});
}

https://godbolt.org/z/qMvKcc8ff

template <char... Cs>
[[nodiscard]] constexpr auto operator""_number() {
    int result = 0;
    ((result = result * 10 + (Cs - '0')), ...);
    return result;
}

https://godbolt.org/z/7vs1d51no