标准库中没有std::identity是有原因的吗

Is there a reason why there is not std::identity in the standard library?

本文关键字:identity std 标准      更新时间:2023-10-16

在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());

上面的一行似乎更清楚地说明了这一意图。