vendredi 31 janvier 2020

Can't move a smart ptr into a std::function

I want to create an std::function that captures a auto_ptr/unique_ptr into but can't properly do it. I need a solution that works on c++11 but I couldn't even figure out how to do it on c++14

Following examples work with c++11 (IncByTwenty) abd c++14 (IncByThirty). However When I change those auto s to Func, it no longer compiles.

typedef std::function<int( int )> Func;
Func IncByTen = std::bind( []( const int& p, int t ) -> int
{
    return p + t;  
}, 10, std::placeholders::_1 );

std::auto_ptr< int > pTwenty(new int(20));
// should have work in c++11 i think? cant assign to Func type
auto IncByTwenty = std::bind( []( const std::auto_ptr< int >& p, int t ) -> int
{
    return ( *p ) + t;  
}, std::move( pTwenty ), std::placeholders::_1 );

std::unique_ptr< int > pThirty = std::make_unique< int >( 30 );
// c++14  cant assign to Func type
auto IncByThirty  = [p{std::move(pThirty) }]( int t ) -> int
{
    return ( *p ) + t;  
};

std::cout << IncByTen(3) << " "  << IncByTwenty(4) << " " << IncByThirty(5);

Am I doing it wrong? Otherwise I need to create something that is assignable to std::function and it needs to capture some local variables using move operator. Any suggestions?

Aucun commentaire:

Enregistrer un commentaire