保留函子作为变量

Toj*_*oji 6 c++ functor

我正在研究资源管理类,并希望让用户为"ReleaseResource"方法提供一个函子,作为资源管理器构造函数的一部分.从那里请求资源时,将提供functor作为我将返回的shared_ptr的删除器,以便在不再使用资源时调用适当的方法.

我遇到的问题是,这要求我将仿函数存储在我的班级中,而我并不完全确定如何做到这一点.通常在使用仿函数时,您可以像这样模拟函数:

template<class MyFunctor> MyMethod(MyFunctor f) {
    f();
}
Run Code Online (Sandbox Code Playgroud)

如果您打算在该函数的范围内使用该仿函数,这很好,但由于该模板超出了该函数的范围我不知道您将如何指定适当类型的变量来存储仿函数供以后使用.

任何人都能指出我在正确的方向吗?

Joh*_*itb 8

template<class MyFunctor> MyMethod(MyFunctor f) {
    boost::function<void()> g = f;
    g();
}
Run Code Online (Sandbox Code Playgroud)

传递给boost::function的类型是函数类型.例如,int(bool, char)是返回int并获取bool和char的函数的类型.也就是说,如果你想立即构建shared_ptr,你不需要将functor存储在某个地方(boost::function需要new操作符,即使对于非常小的仿函数,它也会使用特殊的技巧来仅使用堆栈分配(小缓冲区)优化)):

template<class MyFunctor> MyMethod(MyFunctor f) {
    boost::shared_ptr<T> ptr(new T, f);
}
Run Code Online (Sandbox Code Playgroud)

boost :: function是tr1下一个官方C++标准的一部分,也将成为其中的一部分.例:

struct Manager {
    template<typename Deleter>
    Manager(Deleter d) 
        :deleter(d) {

    }

    boost::shared_ptr<Resource> allocate() {
        ...
        return boost::shared_ptr<Resource>(resource, deleter);
    }

private:
    boost::function<void(Resource *)> deleter;
};
Run Code Online (Sandbox Code Playgroud)