标准库中没有std::identity是有原因的吗
Is there a reason why there is not std::identity in the standard library?
在C++中处理泛型代码时,我会发现std::identity
函子(如std::negate
(非常有用。为什么标准库中不存在此项?
在引入std::identity后不久,问题开始出现,首先是与cpp98之前的std::dentity定义冲突,这些定义显示为扩展:https://groups.google.com/a/isocpp.org/forum/#!主题/std提案/vrrtKvA7cqo这个网站可能会为它提供更多的历史。
由于C++20,存在一个具有operator()
模板成员函数的std::identity
函子类型。此函数调用运算符返回其参数。
例如,如果您有这样一个函数模板:
template<typename T, typename Operation>
void print_collection(const T& coll, Operation op) {
std::ostream_iterator<typename T::value_type> out(std::cout, " ");
std::transform(std::begin(coll), std::end(coll), out, op);
std::cout << 'n';
}
并且想要打印vec
:的元素
std::vector vec = {1, 2, 3};
你会做一些类似的事情:
print_collection(vec, [](auto val) { return val; });
使用std::identity
,您可以执行以下操作:
print_collection(vec, std::identity());
上面的一行似乎更清楚地说明了这一意图。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何从 std::atomic 中提取指针 T<T>?
- 为什么 std::unique 不调用 std::sort?
- 什么是 std::identity 以及如何使用它
- 标准库中没有std::identity是有原因的吗