为什么流不能绑定?

Why can't ofstream be bound with bind?

本文关键字:绑定 不能 为什么      更新时间:2023-10-16

我想通过将公共参数(包括开放的流)绑定到多次调用的函数来减小代码大小,但 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>
           ^

我做错了什么还是无法绑定流(为什么不)?

您收到的错误消息非常清楚:

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);
如果将

移动到绑定中,则代码是合法的C++11:

auto writer2 = bind(writer, std::move(outfile), placeholders::_1);

如果这仍然不适合您,那是因为 gcc 尚未实现可移动流。 我知道这项工作正在进行中,但我不知道它落在哪个 gcc 版本中。