方法 1

#include <iostream>

// 通过递归实现
template <int Beg, int End>
struct static_for
{
    template <typename Fn>
    void operator()(const Fn& fn) const
    {
        if (Beg < End)
        {
            fn(Beg);
            static_for<Beg+1, End>()(fn);   // 最后一次,2个数相等了,会调用下面的 static_for<N, N>
        }
    }
};

template <int N>
struct static_for<N, N>
{
    template <typename Fn>
    void operator()(Fn const& fn) const
    {
        std::cout << "static_for<N, N>" << std::endl;
    }
};


int main() {
    static_for<0, 5>()([&](int i){
        std::cout << i << std::endl;
    });
    return 0;
}

方法 2

template<bool Cond>
struct my_enable_if {
};

template<>
struct my_enable_if<true> {
    typedef void type;
};

template<int Beg, int End, typename Fn>
typename my_enable_if<Beg == End>::type static_for(Fn const &fn) {
}

template<int Beg, int End, typename Fn>
typename my_enable_if<Beg != End>::type static_for(Fn const &fn) {
    fn(Beg);
    static_for<Beg + 1, End>(fn);
}

int main() {

    static_for<0, 5>([&](int i){
        std::cout << i << std::endl;
    });

    return 0;
}
posted on 2022-09-14 09:48  残月影歌  阅读(135)  评论(0编辑  收藏  举报