java - C++中接口的匿名实现
问题描述
C++ 是否支持像 Java 这样的接口的匿名实现?
类似于以下代码的内容:
Runnable myRunnable =
new Runnable(){
public void run(){
System.out.println("Runnable running");
}
}
解决方案
您可以通过创建从您定义的接口继承的匿名类的实例来非常接近。
例子:
#include <iostream>
struct Runnable {
virtual ~Runnable() = default;
virtual void operator()() = 0;
};
int main() {
struct : Runnable { // anonymous implementation of interface
void operator()() override {
std::cout << "Run Forrest\n";
}
} myRunnable;
myRunnable(); // prints Run Forrest
}
这是一个人为的例子,将基类指针指向不同匿名实现的Runnable
实例std::vector<std::unique_ptr<Runnable>>
。正如您在此处看到的,使实现匿名化几乎没有用处。匿名类型是简单的std::remove_reference_t<decltype(*instance)>
。
#include <iostream>
#include <memory>
#include <type_traits>
#include <vector>
// Runnable is defined as in the example above
int main() {
// a collection of Runnables:
std::vector<std::unique_ptr<Runnable>> runners;
{ // create a pointer to an instance of one anonymous impl.
struct : Runnable {
void operator()() override {
std::cout << "Foo\n";
}
} *instance = new std::remove_reference_t<decltype(*instance)>;
runners.emplace_back(instance); // save for later
}
{ // create a pointer to an instance of another anonymous impl.
struct : Runnable {
void operator()() override {
std::cout << "Bar\n";
}
} *instance = new std::remove_reference_t<decltype(*instance)>;
runners.emplace_back(instance); // save for later
}
// loop through all `Runnable`s and ... run them:
for(auto& runner : runners) (*runner)(); // prints "Foo\nBar\n"
}