有没有理由在标准库中没有std :: identity?

时间:2016-03-10 04:52:39

标签: c++ function c++11 identity negate

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

2 个答案:

答案 0 :(得分:2)

在引入std :: identity之后不久,问题开始出现,从冲突到std :: identity的pre-cpp98定义开始,显示为扩展名:https://groups.google.com/a/isocpp.org/forum/#!topic/std-proposals/vrrtKvA7cqo 这个网站可能会为它提供更多的历史记录。

答案 1 :(得分:1)

从C ++ 20开始,存在一个std::identity仿函数类型和一个operator()模板成员函数。此函数调用运算符返回其参数。


例如,如果您有这样的功能模板:

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

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

相关问题