感谢 @ecatmur 的回答和评论的大量帮助,我有了以下解决方案,我邀请评论。我本来希望能够boost::make_function_output_iterator正常工作,但库中似乎存在一个错误,无法定义赋值运算符。
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
#include <cassert>
class counting_output_iterator
{
public:
counting_output_iterator& operator=(const counting_output_iterator&) { return *this; };
explicit counting_output_iterator(std::size_t& count) : m_count(count) {}
template<typename T> void operator=(const T&) {}; //NULL op
using iterator_category = std::output_iterator_tag;
using value_type = void;
using difference_type = void;
using pointer = void;
using reference = void;
counting_output_iterator& operator*() { return *this; }
counting_output_iterator& operator++() { ++m_count; return *this; }
std::size_t& m_count;
};
int main(int, char*[])
{
std::vector<int> arr{ 1,2,3,4 };
std::size_t count = 0;
std::copy(std::begin(arr), std::end(arr), counting_output_iterator{ count } );
assert(count == 4u);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
174 次 |
| 最近记录: |