I'd like to reduce code size by binding common arguments (including an open ofstream) to a function called multiple times but both clang and gcc refuse to compile this program:
#include "functional"
#include "fstream"
using namespace std;
void writer(ofstream& outfile, int a) {
outfile << "asdf " << a;
}
int main() {
ofstream outfile("test");
writer(outfile, 3);
auto writer2 = bind(writer, outfile, placeholders::_1);
writer2(1);
writer2(2);
writer2(3);
return 0;
}
Clang error doesn't look helpful but gcc gives:
/opt/local/gcc-4.9.1/include/c++/4.9.1/tuple:140:42: error: use of deleted function ‘std::basic_ofstream<char>::basic_ofstream(const std::basic_ofstream<char>&)’
: _M_head_impl(std::forward<_UHead>(__h)) { }
^
In file included from testi.cpp:2:0:
/opt/local/gcc-4.9.1/include/c++/4.9.1/fstream:602:11: note: ‘std::basic_ofstream<char>::basic_ofstream(const std::basic_ofstream<char>&)’ is implicitly deleted because the default definition would be ill-formed:
class basic_ofstream : public basic_ostream<_CharT,_Traits>
^
Am I doing something wrong or is binding an ofstream not possible (why not)?
The error message you are receiving is pretty clear:
The copy constructor is deleted, so
std::ofstream
cannot be copied. If you want to wrap an argument tostd::bind
in a reference, usestd::ref
.