在Java中,我们可以像这样使用匿名类来实现一个接口:
自Java 8开始:
我们该如何在C++中实现它?我写了以下代码,但是遇到了编译错误:
interface
。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);
}
}
自Java 8开始:
System.out.println(testIf("", String::isEmpty));
我们该如何在C++中实现它?我写了以下代码,但是遇到了编译错误:
#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;
}
错误:没有与参数列表匹配的函数模板“testIf”实例,参数类型为:std::string
,class <unnamed>
这里出了什么问题?还有其他的解决方法吗?
谢谢!