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

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

在处理 C++ 中的泛型代码时,我会发现 std::identity 仿函数(如 std::negate)非常有用。标准库中不存在这是否有特殊原因?

引入 std::identity 后不久,问题开始出现,首先是与作为扩展出现的 std::identity pre-cpp98 定义的冲突:https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/vrrtKvA7cqo 该站点可能会提供更多历史记录。

自 C++20 起,有一个带有 operator() 模板成员函数的 std::identity 仿函数类型。这个函数调用运算符 returns 它的参数。


比如你有这样一个函数模板:

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

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