gpt4 book ai didi

java - C++中接口(interface)的匿名实现

转载 作者:行者123 更新时间:2023-12-05 00:43:34 25 4
gpt4 key购买 nike

C++ 是否支持像 Java 这样的接口(interface)的匿名实现?

类似下面的代码:

Runnable myRunnable =
new Runnable(){
public void run(){
System.out.println("Runnable running");
}
}

最佳答案

您可以通过创建一个继承自您定义的接口(interface)的匿名类的实例来非常接近。

例子:

#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"
}

关于java - C++中接口(interface)的匿名实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69183440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com