gpt4 book ai didi

c++ - 标准算法比较器接受不同类型的对象是否合法?

转载 作者:可可西里 更新时间:2023-11-01 18:26:32 25 4
gpt4 key购买 nike

An answer recently posted on Stack Overflow展示了为标准算法提供采用不同类型操作数的比较器的代码:

2. Use a comparator with templated operator().

Instead of using a lambda, define a functor with a templated operator().

struct comparator
{
template<typename T, typename U>
bool operator()(T const& lhs, U const& rhs) const {
return lhs.mCommonField < rhs.mCommonField;
}
};

Then, it's as easy as:

std::sort(aStructs.begin(), aStructs.end(), comparator{});
std::sort(bStructs.begin(), bStructs.end(), comparator{});
// ...
std::set_intersection(aStructs.begin(), aStructs.end(),
bStructs.begin(), bStructs.end(),
std::back_inserter(intersection),
comparator{}
);

Just note that as there is a template in the comparator, it must be declared outside of function scope. Live example on Coliru Viewer.

显然,这至少在实践中有效,有效的现场演示证明了这一点。

但是标准严格允许吗?

最佳答案

标准中的相应部分是 §25.4。对类型的唯一要求 Compare参数在 §25.4/2 中:

Compare is a function object type. The return value of the function call operation applied to an object of type Compare, when contextually converted to bool, yields true if the first argument of the call is less than the second, and false otherwise. Compare comp is used throughout for algorithms assuming an ordering relation. It is assumed that comp will not apply any non-constant function through the dereferenced iterator.

换句话说,当被调用时,它不能改变迭代器指向的值,并且应该对值产生严格的弱排序。由于该比较器满足这两个要求,是的,它是合法的!

事实上,这种比较仿函数正是N3421 - Making Operator Functors greater<> 中提出的。 ,现在是 C++14 标准的一部分。它提供了void标准库仿函数的特化,可以完善与相应运算符(如果有)的前向比较。例如(取自提案文件):

namespace std
{
template <> struct greater<void> {
template <class T, class U> auto operator()(T&& t, U&& u) const
-> decltype(std::forward<T>(t) > std::forward<U>(u))
{ return std::forward<T>(t) > std::forward<U>(u); }
};
}

关于c++ - 标准算法比较器接受不同类型的对象是否合法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22461779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com