Oct 17, 2025

[C++][template] Double checked Stop technique

godbolt:
https://godbolt.org/z/Yenv16xzj

#include <functional>
#include <iostream>
#include <optional>


template <size_t I, typename F>
constexpr std::optional<int> ApplyIndexForOverflow(F f) {
    return ApplyIndexForOverflow<I - 1>(f);
}

template <size_t I, typename F>
constexpr std::optional<int> ApplyIndexFor(F f) {
    if (I == 0) {
        return std::nullopt;
    }
    // double checked stop; otherwise introduced stack overflow
    // from the compiler runtime due to has to instantiate
    // unbounded template instance, like above `ApplyIndexForOverflow`
    return ApplyIndexFor<(I == 0 ? 0 : I - 1 )>(f);
}

template <size_t I, typename F>
constexpr std::optional<int> ApplyIndexForConstexpr(F f) {
    if constexpr(sizeof(F) == 1){
        return I;
    }
    if constexpr(I - 1 == 0){
        return std::nullopt;
    } else {
        return ApplyIndexForConstexpr<I-1>(f);
    }
}

int main() {
 auto run = []{};
 ApplyIndexForOverflow<100>(run);
 ApplyIndexFor<100>(run);
 ApplyIndexForConstexpr<100>(run);
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.