How do I expand a tuple into variadic template function's arguments?

前端 未结 13 1011
旧时难觅i
旧时难觅i 2020-11-22 07:49

Consider the case of a templated function with variadic template arguments:

template Tret func(const T&... t);
         


        
13条回答
  •  孤街浪徒
    2020-11-22 08:26

    1) if you have a readymade parameter_pack structure as function argument, you can just use std::tie like this:

    template 
    void tie_func(std::tuple t, Args&... args)
    {
     std::tie(args...) = t;
    }
    
    int main()
    {
     std::tuple t(2, 3.3, "abc");
    
     int i;
     double d;
     std::string s;
    
     tie_func(t, i, d, s);
    
     std::cout << i << " " << d << " " << s << std::endl;
    }
    

    2) if you don't have a readymade parampack arg, you'll have to unwind the tuple like this

    #include 
    #include 
    #include 
    
    
    
    template
    struct apply_wrap {
        template
        static R applyTuple( std::function& f, const std::tuple& t, UnpackedArgs... args )
        {
            return apply_wrap::applyTuple( f, t, std::get( t ), args... );
        }
    };
    
    
    template<>
    struct apply_wrap<0>
    {
        template
        static R applyTuple( std::function& f, const std::tuple&, UnpackedArgs... args )
        {
            return f( args... );
        }
    };
    
    
    
    template
    R applyTuple( std::function& f, std::tuple const& t )
    {
        return apply_wrap::applyTuple( f, t );
    }
    
    
    
    int fac(int n)
    {
        int r=1;
        for(int i=2; i<=n; ++i)
            r *= i;
        return r;
    }
    
    
    
    int main()
    {
        auto t = std::make_tuple(5);
        auto f = std::function(&fac);
        cout << applyTuple(f, t);
    }
    

提交回复
热议问题