首页 > 解决方案 > 在类中没有使用 C++ 线程的类型名称“类型”

问题描述

我目前在使用 c++ 线程时遇到了问题。我有以下错误:

/usr/include/c++/4.8/thread:140:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (TextMove::*)(); _Args = {}]’
textMove.cc:8:40:   required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (TextMove::*)()>()>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (TextMove::*)()>()>’
         _M_invoke(_Index_tuple<_Indices...>)

但我的代码似乎正确使用了这些功能:

class TextMove : Text{

public:
    TextMove(Viewport *v,rgb_matrix::VFont *f,rgb_matrix::Color *c,rgb_matrix::Color *bg,char* content,int extra) : Text(v,f,0,0,c,bg,content,extra){
        index = 0;
        limit = v->getX();
    }
    void play(int speed);
    void playThread(int speed);
private:
    void draw();
    int index;
    pthread_t thread;
    int limit;
};
void TextMove::play(int speed){
    std::thread t(&TextMove::playThread,speed);
    t.join();
}

void TextMove::playThread(int speed) {
    index = 0;
    while(_x>limit){
        draw();
        sleep(speed);
        _x--;
    }
}

我不知道是不是因为我在课堂上使用它,但我暂时没有发现问题。

标签: c++

解决方案


正如Smit Shah在评论中指出的那样,您可以:

  • 使用以下std::thread构造函数
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

为了传递this论据。

    std::thread t(&TextMove::playThread , this , speed);
    t.join();
  • 或者您可以在构造线程时简单地传递一个 lambda。
    std::thread t([this , &speed]{playThread(speed);});
    t.join();

推荐阅读