簡體   English   中英

錯誤:無法從 '<brace-enclosed initializer list> ' 到 'std::tuple<void (xxx::*)(), xxx> '</void></brace-enclosed>

[英]error: could not convert from '<brace-enclosed initializer list>' to 'std::tuple<void (xxx::*)(), xxx>'

在 godbolt.org 中編譯我的代碼時,我遇到以下錯誤:

In file included from <source>:5:
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/thread: In instantiation of 'std::thread::_State_impl<_Callable>::_State_impl(_Args&& ...) [with _Args = {void (Robot::*)(), Robot&}; _Callable = std::thread::_Invoker<std::tuple<void (Robot::*)(), Robot> >]':
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/thread:226:20:   required from 'static std::thread::_State_ptr std::thread::_S_make_state(_Args&& ...) [with _Callable = std::thread::_Invoker<std::tuple<void (Robot::*)(), Robot> >; _Args = {void (Robot::*)(), Robot&}; std::thread::_State_ptr = std::unique_ptr<std::thread::_State>]'
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/thread:149:46:   required from 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Robot::*)(); _Args = {Robot&}; <template-parameter-1-3> = void]'
<source>:154:51:   required from here
/opt/compiler-explorer/gcc-10.2.0/include/c++/10.2.0/thread:211:46: error: could not convert '{std::forward<void (Robot::*)()>((* & __args#0)), std::forward<Robot&>((* & __args#1))}' from '<brace-enclosed initializer list>' to 'std::tuple<void (Robot::*)(), Robot>'
  211 |    : _M_func{{std::forward<_Args>(__args)...}}
      |                                              ^
      |                                              |
      |                                              <brace-enclosed initializer list>
Compiler returned: 1

看起來錯誤是在使用 std::thread 創建線程時出現的。 代碼的簡化版本是:

class Robot {

    private:
        vector<double> position;
        double area_covered;
        mutex mtx;

    public:
        Robot(const vector<double> &initial_position) {
            position = initial_position;
            area_covered = 0.0;
        }


        void get_area() {
            // ...
        }
};

int main () {
    vector<vector<double> > path{
      {0.00359, -0.0013},   {0.00608, -0.00281},  {0.00756, -0.0027} };
    Robot r3(path[0]);
    std::thread thread1(&Robot::get_area, r3); // one thread
    thread1.join();
}

問題是像這樣將r3傳遞給線程構造函數將嘗試進行復制,並且Robot不可復制也不可移動(因為std::mutex )。

您可以通過指針傳遞 object:

std::thread thread1(&Robot::get_area, &r3);

或者利用<functional>std::reference_wrapper

std::thread thread1(&Robot::get_area, std::ref(r3));

在網上看到

暫無
暫無

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

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