Re: Storing noncopyable but movable object in std::function
On 31 Okt., 06:43, Ralph Zhang wrote:
Suppose I have a functor s, which is noncopyable but movable, how can
I store it in a std::function?
You can't. The wrapped functor has to be CopyConstructible. This is a
requirement std::function imposes on its to-be-wrapped functors.
The easy solution would be to add a layer of indirection with the help
of shared_ptr:
struct forward_tag {};
namespace { const forward_tag fwd = {}; }
template<class Func>
class indirect_shared_functor
{
public:
template<class...Args>
explicit indirect_shared_functor(forward_tag,Args&&...args)
: pfun(std::make_shared<Func>(std::forward<Args>(args)...))
{}
template<class...Args>
typename std::result_of<Func(Args...)>::type
operator()(Args...args) const {
return (*pfun)(std::forward<Args>(args)...);
}
private:
std::shared_ptr<Func> pfun;
};
:::
S s;
std::function<void()> fun = indirect_shared_functor<S>(fwd,move(s));
(untested)
Note1: std::bind is not needed here. std::function accepts any
callable functor if the signatures are compatible, not just bind
expression objects.
Note2: Keep in mind that if you copy fun, the copy will indirectly
refer to the same function object of type S. If you want to avoid the
state sharing here you have to always move std::function objects and
avoid copying them.
Cheers!
SG
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]