How to store variadic template arguments?

前端 未结 4 2181
迷失自我
迷失自我 2020-11-27 09:56

Is it possible to store a parameter pack somehow for a later use?

template 
class Action {
private:        
    std::function

        
4条回答
  •  借酒劲吻你
    2020-11-27 10:38

    This question was from C++11 days. But for those finding it in search results now, some updates:

    A std::tuple member is still the straightforward way to store arguments generally. (A std::bind solution similar to @jogojapan's will also work if you just want to call a specific function, but not if you want to access the arguments in other ways, or pass the arguments to more than one function, etc.)

    In C++14 and later, std::make_index_sequence or std::index_sequence_for can replace the helper::gen_seq tool seen in 0x499602D2's solution:

    #include 
    
    template 
    class Action
    {
        // ...
        template 
        void func(std::tuple& tup, std::index_sequence)
        {
            f(std::get(tup)...);
        }
    
        template 
        void func(std::tuple& tup)
        {
            func(tup, std::index_sequence_for{});
        }
        // ...
    };
    

    In C++17 and later, std::apply can be used to take care of unpacking the tuple:

    template 
    class Action
    {
        // ...
        void act() {
            std::apply(f, args);
        }
    };
    

    Here's a full C++17 program showing the simplified implementation. I also updated make_action to avoid reference types in the tuple, which was always bad for rvalue arguments and fairly risky for lvalue arguments.

提交回复
热议问题