2

Possible Duplicate:
What is predicate in C++?

When I read the C++ primer, there is a defined term which is predicate.

The definition is this :

Functions that returns a type that can be converted to bool. Often used by the generic algorithms to test elements . predicates used by the library are either unary (taking one argument) or binary(taking two).

Anyone that returns a type that can be converted to bool can be predicate ! Right? Or there are some other restrictive conditions.

Thanks!

Community
  • 1
  • 1
Jerikc XIONG
  • 3,517
  • 5
  • 42
  • 71
  • 1
    Imagine you're removing all vowels in a string. Normally, you'd do something similar to (ignoring the `erase` call for simplicity) `std::remove_if(std::begin(str), std::end(str), isVowel);`. In this case, `isVowel` is the predicate, which takes one character and returns true if it's a vowel. You can apply this concept to anything of this nature. – chris Nov 27 '12 at 02:05
  • 2
    Formally in C++, there is no definition of what is a predicate, that comes from logic to name parameters from many C++ standard library functions. Like in `InputIterator find_if(InputIterator first, InputIterator last, Predicate pred)`. BTW, a **functor** also can be a predicate to be used with those functions. – Murilo Vasconcelos Nov 27 '12 at 02:05
  • @jogojapan Yes. But it had closed. I want to get more informations about it.thanks! – Jerikc XIONG Nov 27 '12 at 02:08

1 Answers1

3

There's no formal definition of a predicate in the context of C++ (that I know of anyway), but it generally means a function that can be used in a true/false context.

Here's a possible implementation of count_if from cppreference that illustrates what it's talking about:

template<class InputIt, class UnaryPredicate>
typename iterator_traits<InputIt>::difference_type
    count_if(InputIt first, InputIt last, UnaryPredicate p)
{
    typename iterator_traits<InputIt>::difference_type ret = 0;
    for (; first != last; ++first) {
        if (p(*first)) {
            ret++;
        }
    }
    return ret;
}

p must return something that can be used inside of an if statement is what it basically boils down to.

For example:

class T {};

T f(int x)
{
    return T();
}

This is not a valid predicate for count_if because T is not implicitly convertible to a bool.

In other words:

if (f(4)) { }

Is uncompilable code.

If, however, T could be implicitly converted to a bool, f would be an acceptable predicate (though very odd).

Corbin
  • 33,060
  • 6
  • 68
  • 78