5

ラムダ内でboost::packaged_taskを移動して呼び出したい。

しかし、私はエレガントな解決策を見つけることができません。

例:これはコンパイルされません。

        template<typename Func>
        auto begin_invoke(Func&& func) -> boost::unique_future<decltype(func())> // noexcept
        {   
            typedef boost::packaged_task<decltype(func())> task_type;

            auto task = task_type(std::forward<Func>(func));
            auto future = task.get_future();

            execution_queue_.try_push([=]
            {
                try{task();}
                catch(boost::task_already_started&){}
            });

            return std::move(future);       
        }

    int _tmain(int argc, _TCHAR* argv[])
    {
        executor ex;
        ex.begin_invoke([]{std::cout << "Hello world!";});
       //error C3848: expression having type 'const boost::packaged_task<R>' would lose some const-volatile qualifiers in order to call 'void boost::packaged_task<R>::operator ()(void)'
//          with
//          [
//              R=void
//          ]
        return 0;
    }

私のかなり醜い解決策:

    struct task_adaptor_t
    {
        // copy-constructor acts as move constructor
        task_adaptor_t(const task_adaptor_t& other) : task(std::move(other.task)){}
        task_adaptor_t(task_type&& task) : task(std::move(task)){}
        void operator()() const { task(); }
        mutable task_type task;
    } task_adaptor(std::move(task));

    execution_queue_.try_push([=]
    {
        try{task_adaptor();}
        catch(boost::task_already_started&){}
    });

packaged_taskをそれを呼び出すラムダに移動する「適切な」方法は何ですか?

4

2 に答える 2

2

std :: bind(またはmove対応タイプに関して同等のもの)を適切に実装すると、bindとC++0xラムダを次のように組み合わせることができるはずです。

task_type task (std::forward<Func>(func));
auto future = task.get_future();

execution_queue_.try_push(std::bind([](task_type const& task)
{
    try{task();}
    catch(boost::task_already_started&){}
},std::move(task)));

return future;

ところで:futureはローカルオブジェクトであるため、futureを移動するstd::moveは必要ありません。そのため、すでにコピーの省略の可能性があり、コンパイラがその省略を実行できない場合は、「future」から戻り値を作成するように移動する必要があります。この場合のstd::moveの明示的な使用は、実際にはコピー/移動の省略を禁止する可能性があります。

于 2010-12-20T20:56:43.950 に答える
2

ラムダへの移行について投稿した同様の質問があります。C ++ 0xには、移動キャプチャ構文はありません。私が思いついた唯一の解決策は、ある種のプロキシ関数オブジェクトでした。

template<typename T, typename F> class move_capture_proxy {
    T t;
    F f;
public:
    move_capture_proxy(T&& a, F&& b) 
        : t(std::move(a)), f(std::move(b)) {}
    auto operator()() -> decltype(f(std::move(b)) {
        return f(std::move(b));
    }
};
template<typename T, typename F> move_capture_proxy<T, F> make_move_proxy(T&& t, F&& f) {
    return move_capture_proxy<T, F>(std::move(t), std::move(f));
}

execution_queue.try_push(make_move_proxy(std::move(task), [](decltype(task)&& ref) {
    auto task = std::move(ref);
    // use task
});

私は実際にこのコードを試したことがないことに注意してください。可変個引数テンプレートを使用するとさらに便利になりますが、MSVC10にはそれらがないため、実際にはわかりません。

于 2010-12-20T19:08:37.007 に答える