Cleanest way(s) to negate a predicate in C++11?

Started by
6 comments, last by Ravyne 10 years, 9 months ago

The problem: I have a predicate bool pred(const T&) which I can feed to an algorithm like partition, but what I want is its negation (!pred). I'd prefer a solution that works regardless of what pred is exactly, but at least the solution has to work if pred is a named lambda.

I can come up with three ways of getting the negation:

1) [](const T& t){return !pred(t);} or

2) bind(logical_not<bool>(), bind(pred, _1)) or

3) not1(function<bool(const T&)>(pred))

but all of them are clumsy. I feel the lambda version (1) may be the easiest to write and read, but on the other hand I like the bind version (2) because it avoids the need to specify T's type explicitly. (3) has nothing going for it. Am I overlooking something? I thought about writing a template function function<...> neg(pred), but could not think of a way to deduce the parameter type of the callable, which would be necessary to specify a correct return type for neg, and apparently function is also less efficient than raw lambdas and function pointers.

Advertisement

I would say the first is the easiest, and with C++14 planned generic lambda's, the need to specify T may disappear.

The problem: I have a predicate bool pred(const T&) which I can feed to an algorithm like partition, but what I want is its negation (!pred). I'd prefer a solution that works regardless of what pred is exactly, but at least the solution has to work if pred is a named lambda.

I can come up with three ways of getting the negation:

1) [](const T& t){return !pred(t);} or

2) bind(logical_not<bool>(), bind(pred, _1)) or

3) not1(function<bool(const T&)>(pred))

but all of them are clumsy. I feel the lambda version (1) may be the easiest to write and read, but on the other hand I like the bind version (2) because it avoids the need to specify T's type explicitly. (3) has nothing going for it. Am I overlooking something? I thought about writing a template function function<...> neg(pred), but could not think of a way to deduce the parameter type of the callable, which would be necessary to specify a correct return type for neg, and apparently function is also less efficient than raw lambdas and function pointers.

The first one is the only clean solution and the preferred way of doing this in C++11 (http://herbsutter.com/2013/05/16/gotw-3-solution-using-the-standard-library-or-temporaries-revisited/). Why don't you write your predicate in such a way that it takes and "auto" as then your lambda doesn't need to take a type at all.

Worked on titles: CMR:DiRT2, DiRT 3, DiRT: Showdown, GRID 2, theHunter, theHunter: Primal, Mad Max, Watch Dogs: Legion

The first one is the only clean solution and the preferred way of doing this in C++11 (http://herbsutter.com/2013/05/16/gotw-3-solution-using-the-standard-library-or-temporaries-revisited/). Why don't you write your predicate in such a way that it takes and "auto" as then your lambda doesn't need to take a type at all.

I'd love to be able to write (1) with an auto parameter, but I can't, as that is C++14. This is about C++11 solutions.

And since I have to specify the type, I disagree about (1) being clean.

Why specifically do you think (2) is worse? Obviously it's a few more characters than I'd really like to write, but it's actually shorter than (1) as soon as T is replaced with an actual type, expresses my intention clearly, doesn't use anything deprecated and doesn't violate DRY.

What about writing a templatized overload for operator! that can be applied to a predicate such that it returns the inverted predicate in its place?

Then you can use whichever method of the three that you like best without worrying about verbosity, etc -- and the call-site would just be !pred(whatever), like you really want.

EDIT: Nevermind -- missed in your post that you had thought about this already.

throw table_exception("(? ???)? ? ???");

As a proof of concept (only tested with real lambdas, not functors or std:: predicates), you can get close-ish if you're willing to restate the argument type of the predicate with something like this:

template <typename ArgType, typename Pred>
std::function<bool(ArgType)> invert_pred(Pred &pred)
{
return [&pred](ArgType t) { return !pred(t); };
}

From there, you could use some template meta-programming magic to deduce the argument type from the predicate directly, rather than giving it explicitly, as in this Stack Overflow answer.

A few observations about this problem:

  • The thing returned by invert_pred doesn't have to be the same kind of thing as the predicate it takes as an argument. In fact, the closure object makes this impossible for lambdas as far as I can tell -- you can't produce an equivalent closure inside invert_pred as the one at the callsite.
  • Overloading operator! is tricky here because you have to give the original predicate argument type -- but it works as operator!<arg_type>(pred). I believe this would be resolved if you used the meta-programming trick to deduce arg_type automatically.

throw table_exception("(? ???)? ? ???");

Ravyne, can you post a complete program where your function works? I can't get it to work after doing what I thought was the obvious thing to do.

Here it is:


#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

template <typename ArgType, typename Pred>
std::function<bool(ArgType)> invert_pred(Pred &pred)
{
	return [&pred](ArgType t) { return !pred(t); };
}

template <typename ArgType, typename Pred>
std::function<bool(ArgType)> operator!(Pred &pred)
{
	return [&pred](ArgType t) { return !pred(t); };
}

int main(int argc, char* argv[])
{
	std::vector<int> v;
	v.push_back(10);
	v.push_back(11);
	v.push_back(12);

	auto is_twelve = [&](int i) { return i == 12; };

	auto twelve = std::find_if(v.begin(), v.end(), is_twelve);

	auto not_twelve = std::find_if(v.begin(), v.end(), invert_pred<int>(is_twelve));

	auto not_twelve2 = std::find_if(v.begin(), v.end(), operator!<int>(is_twelve));

	//std::cout << twelve

	return 0;
}

Once again, proof of concept, essentially. Not thoroughly tested, the byref params may be superfluous or not, here be dragons, etc. etc.

VS2012 w/ Latest updates.

throw table_exception("(? ???)? ? ???");

This topic is closed to new replies.

Advertisement