使用std :: thread调用重载的成员函数 [英] Calling overloaded member functions using std::thread
问题描述
是否有可能需要使用线程来重载函数?
Is it possible to have overloads for functions that we need to span using threads ?
我有一个简单的类,称为Complex。
I have a simple class called Complex.
class Complex
{
public:
Complex():realPart_(0), imagPart_(0){}
Complex(double rp, double ip) : realPart_(rp), imagPart_(ip) {}
double & real() { return realPart_;}
double & imag() { return imagPart_;}
const double & real() const { return realPart_;}
const double & imag() const { return imagPart_;}
double square() const {return realPart_*realPart_ - imagPart_*imagPart_;}
void display() const
{
std::cout << "Square of the Complex number (" << realPart_ << ") + i (" << imagPart_ << " ) is " << square() << std::endl;
}
void display(unsigned nTimes) const {while(nTimes-- > 0)display();}
private:
double realPart_;
double imagPart_;
};
void Test3()
{
Complex c1(1, 0.74), c2(2, 0.35);
std::thread sqCalc1(&Complex::display, &c1);
std::thread sqCalc2(&Complex::display, &c2);
sqCalc1.join();
sqCalc2.join();
}
构建此代码时会出错。
I get errors when I build this code.
error C2661: 'std::thread::thread' : no overloaded function takes 2 arguments
如果没有不带符号的重载显示函数,那么我显示的代码可以正常工作。
If there is no overloaded display function that takes an unsigned then the code I have shown works fine.
推荐答案
问题与 std :: thread
无关(错误具有误导性),可以通过重新排列代码来显示:
The problem is nothing to do with std::thread
(the error is misleading), as can be shown by rearranging the code:
auto memfunc = &Complex::display;
std::thread sqCalc1(memfunc, &c1);
std::thread sqCalc2(memfunc, &c2);
错误现在将出现在第一行,因为正如其他答案所说,表达式& Complex :: display
指的是一个重载函数,编译器不知道您的意思是什么。
The error will be on the first line now, because as other answers have said, the expression &Complex::display
refers to an overloaded function and the compiler doesn't know which one you mean.
您可以通过强制编译器告诉您要调用的函数的类型(使用强制转换或类似方法)来选择所需的重载:
You can select the desired overload by telling the compiler the type of the function you are trying to call, with a cast or like this:
void (Complex::*memfunc)() const = &Complex::display;
std::thread sqCalc1(memfunc, &c1);
std::thread sqCalc2(memfunc, &c2);
现在您已明确请求显示
重载返回 void
并且不接受任何参数。
Now you've explicitly requested the display
overload that returns void
and takes no arguments.
如果编译器支持C ++ 11别名声明,则可以使更容易阅读:
If your compiler supports C++11 alias declarations you can make that easier to read:
using memfunc_type = void (Complex::*)() const;
memfunc_type memfunc = &Complex::display;
std::thread sqCalc1(memfunc, &c1);
std::thread sqCalc2(memfunc, &c2);
这篇关于使用std :: thread调用重载的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!