簡體   English   中英

c ++ 11 std :: async不能通過引用使用可變參數模板參數

[英]c++11 std::async not working with variadic template parameters by reference

此代碼怎么可能不起作用? 我希望MyThread :: run可與任何類型的參數一起使用,並且參數是通過引用而不是通過值傳遞的。

http://ideone.com/DUJu5M

#include <iostream>
#include <future>
#include <string>

class MyThread {

        std::future<void> future;

    public:

        template<class... Args>
        MyThread(Args&&... myArgs) :
        future(std::async(std::launch::async, &MyThread::run<Args&&...>, this, std::forward<Args>(myArgs)...))
        {}

        template<class... Args>
        void run(Args&&... myArgs) {}
};

int main() {
    std::string x;
    MyThread thread(x); // Not working
    MyThread thread(10); // Working
    return 0;
}

您可以使用std::ref傳遞reference_wrapper 標准庫功能(例如std::bind / std::threadstd::async將自動解壓縮該文件。

int main() {
    std::string x;
    MyThread thread(std::ref(x)); // Not working
    MyThread thread2(10); // Working
    return 0;
}

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM