我想通过将常见参数(包括open ofstream)绑定到多次调用的函数来减少代码大小,但clang和gcc都拒绝编译该程序:
#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错误看起来没有用,但是gcc给出了:
/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>
^
我做错了什么或绑定了一个不可能的流(为什么不)?
答案 0 :(得分:7)
您收到的错误消息非常清楚:
error: use of deleted function
‘std::basic_ofstream::basic_ofstream(const std::basic_ofstream&)’
: _M_head_impl(std::forward(__h)) { }
复制构造函数已删除,因此无法复制std::ofstream
。如果要在参考中将参数包装到std::bind
,请使用std::ref
。
auto writer2 = bind(writer, ref(outfile), placeholders::_1);
答案 1 :(得分:3)
如果你将流转移到绑定中,那么你的代码是合法的C ++ 11:
auto writer2 = bind(writer, std::move(outfile), placeholders::_1);
如果这仍然不适合你,那是因为gcc尚未实现可移动流。我知道这项工作正在进行中,但我不知道它落入哪个gcc版本。