In Java/Kotlin im used to do this:
interface MyInterface {
fun run();
}
And then creating anonymous instances like so:
val actions = arrayOf(
object: MyInterface {
fun run(){
//do something
}
},
object: MyInterface {
fun run(){
//do something
}
}
);
Id like to do something similar in C++ :
class MyClass {
virtual void run();
}
MyClass actions[10] = {
new MyClass(){
void run() {
// something
}
}
}
Is this possible?
5
You might want to have a list of “executor”:
std::vector<std::function<void()>> funcs = {
[](){ std::cout << "First functionn"; },
[](){ std::cout << "Second functionn"; },
// ...
};
Else, C++ allows to declare anonymous classes in some scope when declaring variable, but seems not suitable for your array need:
struct MyInterface {
virtual ~MyInterface() = default;
virtual void run() = 0;
};
void foo()
{
struct : MyInterface {
void run() override { std::cout << "s1n"; }
} s1;
struct : MyInterface {
void run() override { std::cout << "s2n"; }
} s2;
MyInterface* interfaces[] = {&s1, &s2};
for (auto* o : interfaces) {
o->run();
}
}
Demo
2
C++ does not have a complete real equivalent to Java’s anonymous class.
However – if your interface contains one method, you can use std::function
with lambdas to achieve what you need:
#include <functional>
#include <vector>
#include <iostream>
using MyInterfaceFunc = std::function<void(void)>;
int main() {
// Vector of lambdas which are converatble to `MyInterfaceFunc`:
std::vector<MyInterfaceFunc> actions = {
[](){ std::cout << "do something 1n"; },
[](){ std::cout << "do something 2n"; },
};
// ...
// Execute the actions:
for (auto & action : actions ) {
action();
}
}
Output:
do something 1
do something 2
Live demo
5