variadic template class to make a deferred call to a variadic template function

前端 未结 2 627
无人共我
无人共我 2021-01-24 06:07

I can create a template class that stores some values in a property and let me later call a method that call a function with this arg. Like this :

template <         


        
相关标签:
2条回答
  • 2021-01-24 06:38

    You may use something like the following:

    template <typename... Ts> class B
    {
    public:
        std::tuple<Ts...> t;
        B(Ts... args)
            : t(args...)
        {
        }
        void m() { call_f(std::index_sequence_for<Ts>()); }
    
    private:
        template <std::size_t ... Is>
        void call_f(std::index_sequence<Is...>)
        {
            f(std::get<Is>(t)...);
        }
    };
    

    Note that std::index_sequence_for (std::make_index_sequence) and std::index_sequence are C++14 but may be written in C++11.

    Live example.

    0 讨论(0)
  • 2021-01-24 06:41

    http://ideone.com/OPl7Rz

    #include <iostream>
    #include <functional>
    
    using namespace std;
    
    template<typename... T>
    void f(T... a)
    {
        std::initializer_list<int> {(std::cout<<a<<" ", 0)...};
    }
    
    template<typename... T>
    class Defer
    {
        private:
            std::function<void()> func;
    
        public:
            Defer(T... a) : func(std::bind(f<T...>, a...)) {}
            void call() {func();}
    };
    
    
    
    int main()
    {
        Defer<int, float, int, const char*> d(1, 1.1, 2, "Hey");
        d.call();
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题