函数包装器,能够进行移动操作:
#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;
};