Why no emplacement iterators in C++11 or C++14?(为什么在 C++11 或 C++14 中没有定位迭代器?)
问题描述
C++98 有 front_inserter、back_inserter 和 inserter,但在C++11 或 C++14 草案.是否有任何技术原因我们不能拥有 front_emplacer、back_emplacer 和 emplacer?
C++98 has front_inserter, back_inserter, and inserter, but there don't seem to be any emplacement versions of these in C++11 or draft C++14. Is there any technical reason we couldn't have front_emplacer, back_emplacer, and emplacer?
推荐答案
是否有任何技术原因我们不能拥有 front_emplacer、back_emplacer 和 emplacer?
Is there any technical reason we couldn't have front_emplacer, back_emplacer, and emplacer?
不,没有技术原因.作为证明,这里是 back_emplacer 的完整实现以及您的用例 1 的演示...
No, there is no technical reason. As proof, here is a complete implementation of back_emplacer with a demo of your Use Case 1...
#include <iterator>
#include <vector>
#include <iostream>
template<class Container>
class back_emplace_iterator : public std::iterator< std::output_iterator_tag,
void, void, void, void >
{
protected:
Container* container;
public:
typedef Container container_type;
explicit back_emplace_iterator(Container& x) : container(&x) {}
template<class T>
back_emplace_iterator<Container>&
operator=(T&& t)
{
container->emplace_back(std::forward<T>(t));
return *this;
}
back_emplace_iterator& operator*() { return *this; }
back_emplace_iterator& operator++() { return *this; }
back_emplace_iterator& operator++(int) { return *this; }
};
template< class Container >
inline back_emplace_iterator<Container>
back_emplacer( Container& c )
{
return back_emplace_iterator<Container>(c);
}
struct Demo
{
int i;
Demo(int i) : i(i) {}
};
int main()
{
std::vector<int> x = {1,2,3,4,5};
std::vector<Demo> y;
std::copy(x.begin(), x.end(), back_emplacer(y));
for (auto d : y)
std::cout << d.i << std::endl;
}
可能的已知问题:operator= 的通用引用是否隐藏了隐式生成的复制/移动 operator=?如果是这样,则需要以在重载解析中击败通用引用的方式明确定义这些.
Possible Known Issue: Does the universal reference of operator= hide an implicitly generated copy/move operator=? If so these need to be explicitly defined in a way that beats the universal reference in overload resolution.
这篇关于为什么在 C++11 或 C++14 中没有定位迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么在 C++11 或 C++14 中没有定位迭代器?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
