C++Guns – RoboBlog

24.09.2017

C++ Guns - Settings class

Filed under: Allgemein — Tags: — Thomas @ 11:09

Für das nächste große Projekt will ich Einstellungen aus einer Datei lesen und in Performance kritischen Codeabschnitt nutzen.
Die Variablen sollen read-only, also const, sein. So wird ein versehentlichen verändern der Einstellungen verhindert und der Compileroptimierer freut sich auch. Auf getter-Funktionen möchte ich wegen unnötigen Code verzichten.
Wenige Variablen werden besonders häufig benutzt, daher soll keine zusätzliche Tipparbeit entstehen, um erst auf das Einstellungs-Objekt zuzugreifen, und dann auf die eigentliche Variable. Statt

if(settings.L1)

einfach gleich

if(L1)

Also wird es Shortcut Variablen geben.
Um die Lesbarkeit des performance kritischen Codes nicht zu verschlechtern, sollen einige Einstellungs Variablen zur Compilezeit ausgewertet werden, aber erst zur Laufzeit gesetzt. Dies gelingt mittels Code Vervielfältigung. Der Compiler erstellt für jede Variante speziell optimierten Code.

Erste Implementierung:

#ifndef __cpp_if_constexpr
    #error "You need an actual C++17 compiler with feature P0292R2 'constexpr if' for this example"
#endif

#include <iostream>

using namespace std;

struct Settings {
    bool L1 = false;
    bool L2 = false;
};

template<bool L2>
class Algo {
public:
    Algo(const Settings& s)
        : s(s)
    {
    }

    void run() {
        cout << "SWE Settings:\n";
        cout << "L1          " << s.L1 << "\n";
        cout << "shortcut L1 " << L1   << "\n";
        cout << "L2          " << s.L2 << "\n";
        // s.L2 = true; // error. read only

        if constexpr(L2) {
            cout << "L2 template " << L2   << "\n";
        } else {
            cout << "L2 template " << L2   << "\n";
        }
    }

private:
    const Settings s;
    const bool L1 = s.L1;
};


Settings readSettings() {
    Settings s;
    s.L1 = true;
    return s;
}

template<bool L2>
void func(const Settings& s) {
    Algo<L2> swe(s);
    swe.run();
}

int main() {
    cout << boolalpha;

    Settings s = readSettings();

    cout << "Runtime L2 setting: " << s.L2 << "\n";
    if(s.L2) {
        func<true>(s);
    } else {
        func<false>(s);
    }

    s.L2 = !s.L2;
    cout << "\nRuntime L2 setting: " << s.L2 << "\n";
    if(s.L2) {
        func<true>(s);
    } else {
        func<false>(s);
    }
}


No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress