boost :: function_output_iterator从lambda函数构造是不可分配的 [英] boost::function_output_iterator constructed from lambda function is not assignable
问题描述
请考虑以下代码段:
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!
问题是, function_output_iterator
方式是不可指定的,因此不符合迭代器概念,这需要类型 CopyAssignable 。
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.
这不是一个错误,因为 boost函数输出迭代器文档清楚说:
This is not a bug, since boost Function Output Iterator documentation clearly says:
UnaryFunction必须是可分配且可复制的。
UnaryFunction must be Assignable and Copy Constructible.
lambda函数的赋值运算符已删除:
While assignment operator of a lambda function is deleted:
ClosureType& operator=(const ClosureType&) = delete;
所以这种行为在技术上是正确的,但对我来说是有点意想不到的。我认为这是一个完全合理的愿望构造 function_output_iterator
给定一个闭包由lambda函数。这似乎不方便我为什么这个用例导致一个问题。
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. It seems inconvenient to me why this use case causes a problem.
Hm,确定,这个StackOverflow,所以我不得不问一些问题:)这里是:解决这个问题?如何获得一个正确的迭代器给定一个闭包,它的行为像 function_output_iterator
?
Hm, ok, this StackOverflow, so I have to ask some question :) Here it is: how to workaround this? How to obtain a correct iterator given a closure, which acts like function_output_iterator
?
另一个:
推荐答案
只需将闭包保存在 std: :function
:
std::function<void(int)> f = [](int x) { std::cout << x; };
auto it = boost::make_function_output_iterator(f);
这篇关于boost :: function_output_iterator从lambda函数构造是不可分配的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!