lundi 30 novembre 2015

Observable containers

I often face situations where I need to create a selection from a data source, manipulate the selection and feed the changes back to the original data source. Something like

#include <vector>

void manipulate(std::vector<int> &vector) {
    // Manipulate vector...
}

int main() {
    // Data source
    std::vector<int> dataSource{1, 2, 3, 4};

    // Select every second entry
    std::vector<int> selection{v[0], v[2]};

    // Manipulate selection
    manipulate(selection);

    // Feed data back to the data source
    dataSource[0] = selection[0];
    dataSource[2] = selection[1];

    return 0;
}

In order to automate the process of feeding the data back to the data source, I could change the selection to a vector of pointers or references (using std::reference_wrapper) and pass that to the function which manipulates its argument. Alternatively, I could create a class ObservableVector which holds the data source as a member and propagates all changes made to it to the data source. However, in both cases, I would need to change the signature of manipulate to accept a vector of pointers or an ObservableVector. Is there any chance I can keep the original manipulate function (without the need to create a wrapper function) and still automate the process of feeding the data back to the original source?

Aucun commentaire:

Enregistrer un commentaire