class MyClass
{
public:
friend void function(MyClass& mc)
{
std::cout << "Friend function from thread" << std::endl;
}
void init()
{
thr = std::thread(function, this);
thr.join();
}
private:
std::thread thr;
};
int main()
{
std::cout << "This is main function" << std::endl;
MyClass nc;
nc.init();
return 0;
}
Error C2065 'function': undeclared identifier
How to create thread inside a class not using any static function?
I do not know why the lookup of your friend function does not work in this context, maybe someone else knows.
But the fastest way to archive what you want is either a lamdba or declare your function.
Eg
class MyClass;
void function(MyClass& mc);
class MyClass
{
public:
friend void function(MyClass& mc)
...
void init()
{
// either do this
thr = std::thread([this](){function(*this);});
// or this note the std::ref. You are passing a reference. Otherwise there will be a copy
thr = std::thread(&function, std::ref(*this));
thr.join();
}
private:
std::thread thr;
};
....
Well @mkaes beat me to the answer, but I had slightly modified your function()
to accept a pointer to the class and not a reference.
You cannot access a friend function inside a class like you can access other member functions.
function()
doesn't know about the class MyClass
, we have to forward declare the MyClass
class also. #include <iostream>
#include <thread>
class MyClass;
void function(MyClass* mc)
{
std::cout << "Friend function from thread" << std::endl;
}
class MyClass
{
public:
void init()
{
thr = std::thread(function, this);
thr.join();
// function(this);
}
friend void function(MyClass* mc);
private:
std::thread thr;
};
int main()
{
std::cout << "This is main function" << std::endl;
MyClass nc;
nc.init();
return 0;
}
Output:
This is main function
Friend function from thread
EDIT:
As per the discussion in the comments, my first code posted here had the problem that you could not call a member function or access a member variable inside the friend function()
, since the class was defined afterwards. To address that here is the alternative below. But anyways, @mkaes has already answered it in this way from the beginning.
#include <iostream>
#include <thread>
class MyClass;
void function(MyClass* mc);
class MyClass
{
public:
void init()
{
thr = std::thread(function, this);
thr.join();
// function(this);
}
friend void function(MyClass* mc)
{
std::cout << "Friend function from thread" << std::endl;
mc->test();
}
int test(){}
private:
std::thread thr;
};
int main()
{
std::cout << "This is main function" << std::endl;
MyClass nc;
nc.init();
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.