Pointers, Functions, and Arrays in D Programming Language

I am writing a method to output to multiple output streams at once, since I received it right now, this is what I have LogController, LogFileand the LogConsolelast two are implementations of the interface Log.

What I'm trying to do right now is adding a method to LogControllerthat attaches any implementation of the interface Log.

How I want to do this: LogControllerI have an associative array in which pointers to objects are stored Log. When a method is called writeOut LogController, I want it to then execute the elements of the array and call their methods writeOut. The last thing I can do, but the previous one is difficult.

Mage / Utilities / LogController.d

module Mage.Utility.LogController;

import std.stdio;

interface Log {
    public void writeOut(string s);
}

class LogController {
    private Log*[string] m_Logs;

    public this() {

    }

    public void attach(string name, ref Log l) {
        foreach (string key; m_Logs.keys) {
            if (name is key) return;
        }

        m_Logs[name] = &l;
    }

    public void writeOut(string s) {
        foreach (Log* log; m_Logs) {
            log.writeOut(s);
        }
    }
}

Mage / Utilities / LogFile.d

module Mage.Utility.LogFile;

import std.stdio;
import std.datetime;

import Mage.Utility.LogController;

class LogFile : Log {
    private File fp;
    private string path;

    public this(string path) {
        this.fp = File(path, "a+");
        this.path = path;
    }

    public void writeOut(string s) {
        this.fp.writefln("[%s] %s", this.timestamp(), s);
    }

    private string timestamp() {
        return Clock.currTime().toISOExtString();
    }
}

attach, . :

Mage\Root.d(0,0): Error: function Mage.Utility.LogController.LogController.attach (string name, ref Log l) is not callable using argument types (string, LogFile)

:

public void initialise(string logfile = DEFAULT_LOG_FILENAME) {
    m_Log = new LogController();

    LogFile lf = new LogFile(logfile);
    m_Log.attach("Log File", lf);
}

- , ? , . , .

+4
1

D , Log* - *. ref ref Log l - , ++.

, - , , . ref .

+5

Source: https://habr.com/ru/post/1532653/


All Articles