64,637
社区成员
发帖
与我相关
我的任务
分享
template <typename Func>
struct NegateOf
{
NegateOf(Func f) : func(f)
{
}
template <typename ...Args>
bool operator() (Args&&...args)
{
return !func(std::forward<Args>(args)...);
}
protected:
Func func;
};
#include <functional>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <iterator>
template <typename Func>
struct NegateOf
{
NegateOf(Func f) : func(f)
{
}
template <typename ...Args>
bool operator() (Args...args)
{
return !func(args...);
}
protected:
Func func;
};
template <typename Func>
NegateOf<Func> negate_of(Func f)
{
return NegateOf<Func>(f);
}
int main()
{
auto odd = [](int x)
{
return static_cast<bool>(x % 2);
};
//not1
auto even = negate_of(odd);
auto numbers = {3, 7, 6, 5, 4};
auto it = std::find_if(numbers.begin(), numbers.end(), even);
std::cout << "first even number: ";
if (it == numbers.end())
std::cout << "<nil>";
else
std::cout << *it;
std::cout << std::endl;
//not2
{
auto neq = negate_of(std::equal_to<int>());
std::cout << "1 neq 3? " << std::boolalpha << neq(1, 3) << std::endl;
auto seq1 = {1, 3, 7, 4};
auto seq2 = {2, 3, 9, 4};
std::cout << "eq-compare result: \n";
std::transform(
seq1.begin(), seq1.end(), seq2.begin(),
std::ostream_iterator<bool>(std::cout, " "),
std::equal_to<int>());
std::cout << std::endl;
std::cout << "neq-compare result: \n";
std::transform(
seq1.begin(), seq1.end(), seq2.begin(),
std::ostream_iterator<bool>(std::cout, " "),
negate_of(std::equal_to<int>()));
std::cout << std::endl;
}
}