C++

Polymorphic function wrapper (простой аналог std::function)

#include <iostream>

template<class R, class ... Args>
struct function_holder 
{
    virtual R operator() (Args...) = 0;
    virtual ~function_holder() { }
};

template <class T, class R, class ... Args>
struct function_holder_impl : function_holder<R, Args...>
{
    function_holder_impl(T&& t) : func(t) { }

    R operator() (Args ... args) override
    {
        return func(args...);
    }

private:
    T func;
};

template<class>
struct function;

template<class R, class ... Args>
struct function<R(Args...)> {

    template<class T>
    function(T t) 
        : f(new function_holder_impl<T, R, Args...>(std::move(t)))
    { }

    function(function<R(Args...)> const&) = delete;
    function<R(Args...)>& operator= (function<R(Args...)> const*) = delete;

    function(function<R(Args...)> && rhs) : f(rhs.f)
    {
        rhs.f = nullptr;
    }

    function<R(Args...)>& operator= (function<R(Args...)>&& rhs)
    {
        f = rhs.f;
        rhs.f = nullptr;
        return *this;
    }

    R operator() (Args... args)
    {
        return (*f)(args...);
    }
    
    ~function() 
    {
        delete f;
    }

private:
    function_holder<R, Args...> * f;
};

int twice(int i)
{
    return 2 * i;
}

struct callable {
    callable(int k) : k(k) { }

    callable(callable const& r) : k(r.k)
    {
        std::cout << "copy\n";
    }

    callable& operator=(callable const& r) 
    {
        k = r.k;
        std::cout << "assign\n";
        return *this;
    }

    void operator() ()
    {
        std::cout << k << std::endl;
    }

private:
    int k;
};

int main() 
{
    function<int(int)> f = twice;
    std::cout << f(10) << std::endl;
    

    function<int()> g = [] () { return 42; };
    std::cout << g() << std::endl;
    
    callable c(73);
    function<void()> h = c;
    h();
}
Добавлено: 16 Августа 2013 03:44:32 Добавил: Андрей Ковальчук Нравится 0
Добавить
Комментарии:
Нету комментариев для вывода...