Let's say I have the following callback class:
class LogCallback {
public:
virtual void sendLog(std::string log) = 0;
virtual void setErrorCode(int code) = 0;
};
And I have the engine which accepts a callback implementation:
class Engine {
public:
Engine();
virtual ~Engine();
void setCallback(LogCallback* callback);
void start();
private:
LogCallback* logCallback;
};
Now I can create an implementation class:
class OutLogger : public LogCallback {
void sendLog(std::string log) {
cout << "out: " << log << endl;
}
void setErrorCode(int code) {
sendLog("error code " + std::to_string(code));
}
};
And use it:
int process() {
Engine engine;
OutLogger out;
engine.setCallback(&out);
engine.start();
}
In C++11 I can also use an anonymous local class:
int anonymous() {
Engine engine;
class : public LogCallback {
void sendLog(std::string log) {
cerr << "err: " << log << endl;
}
void setErrorCode(int code) {
sendLog("error code " + std::to_string(code));
}
} err;
engine.setCallback(&err);
engine.start();
}
Now there is the question: can I do the same without the explicit anonymous class, inside the function call?
If it was Java I would do it like this:
public class AnonymousClass {
private abstract class LogCallback {
abstract void sendLog(String log);
abstract void setErrorCode(int code);
}
private class Engine {
public void setCallback(LogCallback callback) {
this.callback = callback;
}
public void start() {
if (callback != null) {
callback.sendLog("Starting...");
}
}
private LogCallback callback;
}
public void process() {
Engine engine = new Engine();
engine.setCallback(new LogCallback() {
@Override
void sendLog(String log) {
System.out.println("out: " + log);
}
@Override
void setErrorCode(int code) {
sendLog("error code " + code);
}
});
engine.start();
}
public static void main(String[] args) {
AnonymousClass example = new AnonymousClass();
example.process();
}
}