C++11 在函子中包装std::async 最近我一直在用现代C++进行实验,这让我怀疑我是否可以用一个函子来包装一个类似对象的函数中的异步操作。

C++11 在函子中包装std::async 最近我一直在用现代C++进行实验,这让我怀疑我是否可以用一个函子来包装一个类似对象的函数中的异步操作。,c++11,g++,mingw,C++11,G++,Mingw,我首先发现std::async可以很容易地放在包装函数中,如下所示: #include <iostream> #include <functional> #include <future> template< typename Fn, typename... Args > std::future< typename std::result_of< Fn( Args... ) >::type > LaunchAsync( F

我首先发现std::async可以很容易地放在包装函数中,如下所示:

#include <iostream>
#include <functional>
#include <future>

template< typename Fn, typename... Args >
std::future< typename std::result_of< Fn( Args... ) >::type >
LaunchAsync( Fn&& fn, Args&&... args )
{
    return std::async( std::launch::async, fn, args... );
} 

using namespace std;

int main()
{
    auto addResult = LaunchAsync( []( int a, int b ) { return a + b; }, 1, 2 );   
    cout << addResult.get() << endl;
    return 0;
}
相反,我必须在模板括号中指定函数签名:

auto SubtractAsync = AsyncFunction< std::function< int( int, int ) > >( []( int a, int b ) {
    return a - b;
} );

int main()
{
    auto subtractResult = SubtractAsync( 7, 3 ); // works
    cout << subtractResult.get() << endl;
    return 0;
}
auto SubtractAsync=AsyncFunction>([](int a,int b){
返回a-b;
} );
int main()
{
自动减法结果=减法异步(7,3);//有效

可以使用助手函数模板,比如
make\u pair
是如何工作的。好的,谢谢。我没想到要用函数来包装它。
auto SubtractAsync = AsyncFunction( []( int a, int b ) { // does not work
    return a - b;
} );
auto SubtractAsync = AsyncFunction< std::function< int( int, int ) > >( []( int a, int b ) {
    return a - b;
} );

int main()
{
    auto subtractResult = SubtractAsync( 7, 3 ); // works
    cout << subtractResult.get() << endl;
    return 0;
}
#include <functional>
#include <future>
#include <iostream>

template< typename Fn >
class AsyncFunctor
{
    Fn _fn;
public:
    AsyncFunctor( Fn&& fn ) : _fn( fn ) { }

    template< typename... Args >
    std::future< typename std::result_of< Fn( Args... ) >::type >
    operator()( Args&&... args ) const
    {
        return std::async( std::launch::async, _fn, args... );
    }
};

template< typename Fn > // helper function to handle template parameters
AsyncFunctor< Fn > AsyncFunction( Fn&& fn )
{
    return AsyncFunctor< Fn >( std::move( fn ) );
}

auto AddAsync = AsyncFunction( []( auto a, auto b) { // it works!
    return a + b;
} );

using namespace std;

int main()
{
    auto result = AddAsync( 3, 4 );
    cout << result.get() << endl;
    return 0;
}