我对如何使用这种方法感到困惑。我尝试了以下方法:
std::equal_to(T objA, T objB);
如果我这样使用它,我会出错。但是,我见过无数这样使用它的例子:
pairs1 = mismatch(v1.begin(), v1.end(),
v2.begin(),
equal_to<int>());
应该如何使用这种方法?
示例错误:
prog.cpp: In function ‘int main()’:
prog.cpp:25:31: error: no matching function for call to ‘std::equal_to<int>::equal_to(std::vector<int>&, std::vector<int>&)’
pairs1 = equal_to<int>(v2, v1));
^
In file included from /usr/include/c++/5/string:48:0,
from /usr/include/c++/5/random:40,
from /usr/include/c++/5/bits/stl_algo.h:66,
from /usr/include/c++/5/algorithm:62,
from prog.cpp:2:
/usr/include/c++/5/bits/stl_function.h:352:12: note: candidate: constexpr std::equal_to<int>::equal_to()
struct equal_to : public binary_function<_Tp, _Tp, bool>
^
/usr/include/c++/5/bits/stl_function.h:352:12: note: candidate expects 0 arguments, 2 provided
/usr/include/c++/5/bits/stl_function.h:352:12: note: candidate: constexpr std::equal_to<int>::equal_to(const std::equal_to<int>&)
/usr/include/c++/5/bits/stl_function.h:352:12: note: candidate expects 1 argument, 2 provided
/usr/include/c++/5/bits/stl_function.h:352:12: note: candidate: constexpr std::equal_to<int>::equal_to(std::equal_to<int>&&)
/usr/include/c++/5/bits/stl_function.h:352:12: note: candidate expects 1 argument, 2 provided
equal_to
不是函数,你不能像函数一样直接调用它。它是一个定义了operator()
的类,这意味着您需要创建一个对象并在该对象上调用operator()
。
可能的实现:
template <class T = void>
struct equal_to {
constexpr bool operator()(const T& lhs, const T& rhs) const
{
return lhs == rhs;
}
};
使用示例:
auto test()
{
auto my_comp = equal_to<int>{};
bool b1 = my_comp(2, 3);
// or create a temporary object and call it in one line:
bool b2 = equal_to<int>{}(2, 3);
}
它还有一个专门化,可以推导出传递给operator()
的参数:
template <>
struct equal_to<void> {
template <class T, class U>
constexpr auto operator()(T&& lhs, U&& rhs) const
-> decltype(std::forward<T>(lhs) == std::forward<U>(rhs))
{
return std::forward<T>(lhs) == std::forward<U>(rhs);
}
};
auto test2()
{
using namespace std::string_literals;
auto my_comp = equal_to<>{};
bool b1 = my_comp(2, 3);
bool b2 = my_comp("one string"s, "another string"s);
}