为什么流不能绑定?
Why can't ofstream be bound with bind?
我想通过将公共参数(包括开放的流)绑定到多次调用的函数来减小代码大小,但 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 版本中。
相关文章:
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 为什么结构化绑定不支持可变数组?
- 没有类型结构绑定不起作用?
- 为什么右值不能绑定到非常量左值引用,除了写入临时无效的事实?
- 为什么我不能将常量左值引用绑定到返回 T&&&的函数?
- 为什么我不能绑定?
- QtSql:绑定不会改变SQLite的查询
- 为什么我不能在绑定中使用mem_fn函子?
- 对类型 'A *' 的非常量左值引用不能绑定到不相关的类型 'std::shared_ptr<A>' 的值
- 某些内容可以绑定到非常量引用但不能绑定到常量引用的情况
- | 9 |错误:非静态数据成员'matrix :: row'| 9 |错误:数组绑定不是在']']'令牌|之前的整数常数
- 不能将类型的非常量左值引用绑定到类型的右值
- 为什么指向函数的指针不能绑定到左值引用,而函数可以?
- 纹理绑定不起作用 / C++ / OpenGL
- 如果结构化绑定不能是 constexpr,为什么它们可以在 constexpr 函数中使用?
- boost::与boost:asio绑定在一起.boost::绑定不起作用,从示例中复制
- 绑定不是一个值,而是一个函数(获取该函数的值)
- 为什么c++ 17的结构化绑定不使用{}?
- 套接字绑定不会返回 int
- 我该如何使我的分配器可重新绑定?我能做到这一点,同时保持其字段的私有