Search code examples
javac++cpredicatepredicates

C/C++ Equivalent of Java Predicate


Is there a C/C++ equivalent structure/class of Predicate class in Java?

Specifically, I have a very simple Java code as given below.

import java.util.function.Predicate;
public class JavaPredicates {
    public static void main(String[] args) {
        Predicate<String> i  = (s)-> s.equals("ABCD");
        Predicate<String> j  = (s)-> s.equals("EFGH");
        Predicate<String> k  = (s)-> s.equals("IJKL");
        Predicate<String> l  = (s)-> s.equals("MNOP");
        Predicate<String> m  = (s)-> s.equals("QRST");
        Predicate<String> n  = (s)-> s.equals("UVWYZ");

        System.out.println(i.or(j).or(k).or(l).or(m).or(n).test("ABCD"));
    }
}

I want to implement the same program in C or C++. Is there a default way or an external library for doing this?


Solution

  • C++ has lambdas which appear to be quite similar to the java construct you're using:

    auto i = [](string const & s){return s == "ABCD";}
    

    It doesn't have the built in chaining, but the concept is similar - an inline-defined function. You can use the C++ logic constructs to combine the lambdas into any construct you'd like -- even use a lambda to do it.

    auto final_check = [i,j,k,l,m,n](string const & s){return i(s) || j(s) || k(s).....};