Mik*_*ail 11 c++ lambda boost c++11
请考虑以下代码段:
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!
Run Code Online (Sandbox Code Playgroud)
问题是,function_output_iterator以这种方式构成不可分配,因此不满足迭代器概念,这需要键入要CopyAssignable.
这不是错误,因为boost Function Output Iterator文档清楚地说:
UnaryFunction必须是可分配和复制可构造的.
删除lambda函数的赋值运算符:
ClosureType& operator=(const ClosureType&) = delete;
Run Code Online (Sandbox Code Playgroud)
所以这种行为在技术上是正确的,但对我来说有些出乎意料.我认为function_output_iterator给定一个由lambda函数生成的闭包是一个非常合理的愿望.对我来说这个用例为什么会导致问题似乎不方便.
嗯,好吧,这个StackOverflow,所以我不得不问一些问题:)这里是:如何解决这个问题?给定一个闭包,如何获得一个正确的迭代器,其行为如何function_output_iterator?
还有一个问题:是否值得提出提案或提交错误报告?
Mik*_*ail 11
另一种选择,如果您确定闭包将比迭代器及其副本更长,请将其包装std::ref:
auto f = [](int x) { std::cout << x; };
auto it = boost::make_function_output_iterator(std::ref(f));
Run Code Online (Sandbox Code Playgroud)
演示.
以下是针对修复此特定问题的boost实用程序类的建议:boost :: regular
请参阅boost邮件列表中的相应讨论.
只需将封口保存在std::function:
std::function<void(int)> f = [](int x) { std::cout << x; };
auto it = boost::make_function_output_iterator(f);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
872 次 |
| 最近记录: |