11线程初始化带有成员函数编译错误

11线程初始化带有成员函数编译错误

本文介绍了C ++ 11线程初始化带有成员函数编译错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用C ++ 11线程,我一直在挣扎(可能是愚蠢的)错误。
这是我的示例程序:

  #include< iostream& 
#include< thread>
#include< future>
using namespace std;

class A {
public:
A(){
cout< A constructor\\\
;
}

void foo(){
cout< 我是foo(),我问候你。
}

static void foo2(){
cout< 我是foo2(),我是静态的!\\\
;
}

void operator()(){
cout< 我是运算符()。Hi there!\\\
;
}
};

void hello1(){
cout< 你从外面A类
}

int main(){
A obj;
thread t1(hello1); // it works
thread t2(A :: foo2); // it works
thread t3(obj.foo); // error
thread t4(obj); // it works

t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}

是否可以从纯成员函数启动线程?如果不是,我如何从对象 obj 包装我的 foo 函数,以便能够创建这样的线程?
提前感谢!



这是编译错误:


解决方案

您需要一个不带参数的可调用对象,因此

  (& A :: foo,& obj); 

这具有创建可调用实体的效果,该实体在 obj 上调用 A :: foo



原因是 A 的非静态成员函数采用类型的隐式第一个参数(可能是cv限定) A * 。当你调用 obj.foo()时,你正在有效地调用 A :: foo(& obj)。一旦你知道,上面的咒语是完全有道理的。


I'm just starting to use C++ 11 threads and I've been struggling on a (probably silly) error.This is my example program:

#include <iostream>
#include <thread>
#include <future>
using namespace std;

class A {
public:
  A() {
    cout << "A constructor\n";
  }

  void foo() {
    cout << "I'm foo() and I greet you.\n";
  }

  static void foo2() {
    cout << "I'm foo2() and I am static!\n";
  }

  void operator()() {
    cout << "I'm the operator(). Hi there!\n";
  }
};

void hello1() {
  cout << "Hello from outside class A\n";
}

int main() {
  A obj;
  thread t1(hello1); //  it works
  thread t2(A::foo2); // it works
  thread t3(obj.foo); // error
  thread t4(obj);     // it works

  t1.join();
  t2.join();
  t3.join();
  t4.join();
  return 0;
}

Is it possible to start a thread from a pure member function? If it is not, how can I wrap my foo function from object obj to be able to create such thread?Thanks in advance!

This is the compiling error:

解决方案

You need a callable object taking no parameters, so

thread t3(&A::foo, &obj);

should do the trick. This has the effect of creating a callable entity which calls A::foo on obj.

The reason is that a non-static member function of A takes an implicit first parameter of type (possibly cv qualified) A*. When you call obj.foo() you are effectively calling A::foo(&obj). Once you know that, the above incantation makes perfect sense.

这篇关于C ++ 11线程初始化带有成员函数编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:10