In java we can implement an interface
with Anonymous class like this :
import java.util.function.Predicate;
public class Test {
public static void main(String[] args) {
System.out.println(testIf("", new Predicate<String>() {
@Override
public boolean test(String s) {
return s.isEmpty();
}
}));
}
public static <T> boolean testIf(T t, Predicate<T> predicate) {
return predicate.test(t);
}
}
since Java 8 :
System.out.println(testIf("", String::isEmpty));
how can we do it in c++? I wrote the following code but I'm getting compile error :
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Predicate
{
public:
virtual bool test(T) = 0;
};
template <class T>
bool testIf(T t, Predicate<T> predicate)
{
return predicate.test(t);
}
int main()
{
class : public Predicate <string> {
public:
virtual bool test(string s)
{
return s.length() == 0;
}
} p;
string s = "";
cout << testIf(s, p);
cin.get();
return 0;
}
Error : no instance of function template "testIf" matches the argument list
argument types are: (std::string
, class <unnamed>
)
what's wrong here? are there other ways to do it?
Thanks!