Coe*_*oen 7 c++ closures c++11 std-function
我试图弄清楚当与闭包结合使用时std :: function引擎盖下发生了什么.我还无法绕过它,例如:正在调用什么构造函数?任何人都可以发布一个简单的drop的工作示例来替换std :: function,它支持以下示例中所需的功能吗?
#include <functional>
int main(int argc, char* argv[])
{
int mybool = 5;
auto foo = [&] (int arg) {
return mybool * arg;
};
std::function<int(int)> foo2 = foo;
int result = foo2(42);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是简约的例子:
template <class F>
struct Decomposer;
template <class R, class A>
struct Decomposer<R (A)>
{
typedef R return_type;
typedef A argument_type;
};
template <class F>
struct my_function
{
typedef typename Decomposer<F>::return_type return_type;
typedef typename Decomposer<F>::argument_type argument_type;
return_type operator() (argument_type arg) const {
return (*impl)(arg);
}
template <class From>
my_function(From &&from)
{
struct ConcreteImpl : Impl
{
typename std::remove_reference<From>::type functor;
ConcreteImpl(From &&functor) : functor(std::forward<From>(functor)) {}
virtual return_type operator() (argument_type arg) const override
{
return functor(arg);
}
};
impl.reset(new ConcreteImpl(std::forward<From>(from)));
}
private:
struct Impl {
virtual ~Impl() {}
virtual return_type operator() (argument_type arg) const = 0;
};
std::unique_ptr<Impl> impl;
};
Run Code Online (Sandbox Code Playgroud)
核心思想是使用类型擦除来存储实际的闭包而不知道其类型:请参阅虚拟Impl::operator()和本地定义的特定于类型的持有者ConcreteImpl.
| 归档时间: |
|
| 查看次数: |
1610 次 |
| 最近记录: |