include ifstream as argument to function passing in thread c++

hi,
the thing is i am trying to pass ifstream as argument to thread but i get the following error:-
error: no type named ‘type’ in ‘class std::result_of<void (*(std::basic_ifstream<char>))(std::basic_ifstream<char>)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;
how do i pass the ifstream argument to the function being called on thread
heres my code below



#include <cstdlib>
#include <fstream>
#include <thread>
#include <iostream>
using namespace std;

/*
*
*/
void file_func_1(std::ifstream m_file){
// ifstream m_file;
string line;
while ( getline (m_file,line) ){
cout<<"the line now in is"<<line<<"from thread"<<std::this_thread::get_id()<<endl;
std::this_thread::sleep_for(std::chrono::seconds((rand() % 10) + 1));
}
}
void file_func_2(ifstream m_file){
string line;
while ( getline (m_file,line) ){
cout<<"the line now in is"<<line<<"from thread"<<std::this_thread::get_id()<<endl;
std::this_thread::sleep_for(std::chrono::seconds((rand() % 10) + 1));
}
}
int main(int argc, char** argv) {
std::ifstream m_file;
m_file.open("File_line.txt",ios::in);
int name=8;
std::thread func_th1(file_func_1, (m_file));
// thread func_th2(file_func_2,m_file);
func_th1.join();
// func_th2.join();
return 0;
}

You're trying to copy the stream, but streams are not copyable. You have to move it:

std::thread func_th1(file_func_1, std::move(m_file));

live demo with just that change: http://coliru.stacked-crooked.com/a/944e4f2e0c76116c
Last edited on
actually when i run the modified program on my machine with c++11 enabled it gives this error:-

no type named ‘type’ in ‘class std::result_of<void (*(std::basic_ifstream<char>))(std::basic_ifstream<char>)>’
typedef typename result_of<_Callable(_Args...)>::type result_type;

You'd have to say a bit more about what kind of "c++11" is there on your machine

The program above works with gcc starting at version 5.1: http://melpon.org/wandbox/permlink/TUDVZ082MLGap7DT and clang starting at least at 3.0 (coudln't find an older version online) http://melpon.org/wandbox/permlink/TQ7UWFBVrYZYL9UV

Actually , I see in gcc 4.9.3, where the actual error is "use of deleted function 'std::basic_ifstream<char>::basic_ifstream(const std::basic_ifstream<char>&)'" (attempt to copy a stream), the first line of the error message that says "error:" in it says "usr/local/gcc-4.9.3/include/c++/4.9.3/functional:1665:61: error: no type named 'type' in 'class std::result_of<void (*(std::basic_ifstream<char>))(std::basic_ifstream<char>)>' typedef typename result_of<_Callable(_Args...)>::type result_type;" which sounds like your situation. gcc did not really have C++11 until 5.x
Last edited on
Topic archived. No new replies allowed.