Variadic templates and switch statement?

后端 未结 5 1337
栀梦
栀梦 2020-12-24 13:42

I have the following function which can take N arguments of different types, and forwards them to N functions templated on each individual type, in this manner (example with

5条回答
  •  天涯浪人
    2020-12-24 14:13

    Theoretically you could do binary search of parameter index by yourself:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    template 
    using ic = std::integral_constant;
    
    template 
    bool func2(T) {
        std::cout<
    bool func_impl(ic<0>, ic, std::size_t &, T &&tup) {
        constexpr int index = std::min(N - 1, std::tuple_size{} - 1);
        if (func2>>(std::get(tup))) 
            return true;
        return false;
    }
    
    template 
    bool func_impl(ic, ic n, std::size_t &counter, T &&tup) {
        if (counter == N - 1) {
            return func_impl(ic<0>{}, n, counter, std::forward(tup));
        }
        if (counter < N) {
            return func_impl(ic{}, ic{}, counter, std::forward(tup));
        } else {
            return func_impl(ic{}, ic{}, counter, std::forward(tup));
        }
    }
    
    template 
    bool func(std::size_t& counter, Ts&&... xs) {
        return func_impl(ic{}, ic{}, counter, std::forward_as_tuple(xs...));
    }
    
    int main() {
       std::size_t i = 0;
       func(i, 1, 2, 3, 4); 
    }
    

    [live demo]

提交回复
热议问题