function wrapper

2019-03-07  本文已影响0人  rasishou

函数包装器,能够进行移动操作:


#pragma once

#include<utility>

#include<memory>

using std::move;

using std::unique_ptr;

class function_wrapper{

template<class F>

struct impl_type{

F f;

impl_type(F&&f_):f(move(f_)){}

void call(){

f();

}

};

unique_ptr<impl_type<F>> impl;

public:

template<class F>

function_wrapper(F&&f):impl(new impl_type<F>(move(f))){}

void operator()(){

impl->call();

}

function_wrapper()=default;

function_wrapper(function_wrapper&&other):impl(move(other.impl)){}

function_wrapper&operator=(function_wrapper&&other){

impl=move(other.impl);

return *this;

}

function_wrapper(const function_wrapper&)=delete;

function_wrapper(function_wrapper&)=delete;

function_wrapper&operator=(const function_wrapper&)=delete;

};

但是,unique_ptr<impl_type<F>> impl;这句会报错,因为F未定义。于是为impl_type添加一个父类impl_base,变成unique_ptr<impl_base>impl;:


#pragma once

#include<utility>

#include<memory>

using std::move;

using std::unique_ptr;

class function_wrapper{

struct impl_base{

virtual void call()=0;

virtual ~impl_base(){}

};

unique_ptr<impl_base> impl;

template<class F>

struct impl_type:impl_base{

F f;

impl_type(F&&f_):f(move(f_)){}

void call(){

f();

}

};

public:

template<class F>

function_wrapper(F&&f):impl(new impl_type<F>(move(f))){}

void operator()(){

impl->call();

}

function_wrapper()=default;

function_wrapper(function_wrapper&&other):impl(move(other.impl)){}

function_wrapper&operator=(function_wrapper&&other){

impl=move(other.impl);

return *this;

}

function_wrapper(const function_wrapper&)=delete;

function_wrapper(function_wrapper&)=delete;

function_wrapper&operator=(const function_wrapper&)=delete;

};

上一篇 下一篇

猜你喜欢

热点阅读