【发布时间】:2015-04-25 22:30:08
【问题描述】:
在 java 中,我们可以像这样使用匿名类实现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>)
这里有什么问题?还有其他方法吗?
谢谢!
【问题讨论】:
标签: java c++ interface anonymous-class