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

↘锁芯ラ 提交于 2019-12-02 07:12:29

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;
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!