简体   繁体   English

从lambda函数构造的boost :: function_output_iterator不可赋值

[英]boost::function_output_iterator constructed from lambda function is not assignable

Consider the following code snippet: 请考虑以下代码段:

auto f = [](int x) { std::cout << x; };
auto it = boost::make_function_output_iterator(f);
decltype(it) it2 = it;  // Ok, copied
it2 = it;  // Does not compile, cannot assign!

The problem is, function_output_iterator constructed in this way is not assignable, and thus does not satisfy the Iterator concept, which requires type to be CopyAssignable . 问题是,以这种方式构造的function_output_iterator是不可分配的,因此不满足Iterator概念,它需要类型为CopyAssignable

This is not a bug, since boost Function Output Iterator documentation clearly says : 这不是错误,因为boost Function Output Iterator文档清楚地

UnaryFunction must be Assignable and Copy Constructible. UnaryFunction必须是可分配和复制可构造的。

While assignment operator of a lambda function is deleted: 删除lambda函数的赋值运算符:

ClosureType& operator=(const ClosureType&) = delete;

So this behaviour is technically correct, but for me is somewhat unexpected. 所以这种行为在技术上是正确的,但对我来说有些出乎意料。 I think it is a perfectly reasonable desire to construct function_output_iterator given a closure produced by lambda function. 我认为在给定由lambda函数生成的闭包的情况下构造function_output_iterator是一个非常合理的愿望。 It seems inconvenient to me why this use case causes a problem. 对我来说这个用例为什么会导致问题似乎不方便。

Hm, ok, this StackOverflow, so I have to ask some question :) Here it is: how to workaround this? 嗯,好吧,这个StackOverflow,所以我不得不问一些问题:)这里是:如何解决这个问题? How to obtain a correct iterator given a closure, which acts like function_output_iterator ? 如何在给定闭包的情况下获得正确的迭代器,其作用类似于function_output_iterator

And another one: does it worth to make a proposal or a bug report to boost? 还有一个问题:是否值得提出提案或提交错误报告?

Another option, if you are sure the closure will outlive the iterator and its copies, wrap it with std::ref : 另一种选择,如果你确定闭包将比迭代器及其副本更长,请用std::ref包装它:

auto f = [](int x) { std::cout << x; };
auto it = boost::make_function_output_iterator(std::ref(f));

Demo . 演示

And here is a proposal for a boost utility class fixing this particular problem: boost::regular 以下是针对修复此特定问题的boost实用程序类的建议: boost :: regular

See the corresponding discussion in boost mailing list . 请参阅boost邮件列表中的相应讨论。

Simply save the closure in a std::function : 只需将闭包保存在std::function

std::function<void(int)> f = [](int x) { std::cout << x; };
auto it = boost::make_function_output_iterator(f);

Test snippet. 测试片段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM