function wrapper

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


#pragma once

#include

#include

using std::move;

using std::unique_ptr;

class function_wrapper{

template

struct impl_type{

F f;

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

void call(){

f();

}

};

unique_ptr> impl;

public:

template

function_wrapper(F&&f):impl(new impl_type(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;这句会报错,因为F未定义。于是为impl_type添加一个父类impl_base,变成unique_ptrimpl;:


#pragma once

#include

#include

using std::move;

using std::unique_ptr;

class function_wrapper{

struct impl_base{

virtual void call()=0;

virtual ~impl_base(){}

};

unique_ptr impl;

template

struct impl_type:impl_base{

F f;

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

void call(){

f();

}

};

public:

template

function_wrapper(F&&f):impl(new impl_type(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;

};

你可能感兴趣的:(function wrapper)