在Java中,我们可以实现匿名类的interface
这样实现接口:与++匿名类用C
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>
)
这里有什么问题?还有其他方法可以做到吗?
谢谢!
你可以看看http://stackoverflow.com/questions/991062/passing-unnamed-classes-through-functions – Prashant 2015-02-24 10:41:01