samedi 27 janvier 2018

C++ template meta progr. conditional memory allocation

I am trying to implement a simple Linear-Algebra library (for learning purposes).

Problem => I would like the Matrix template class to either declare a fixed-size array at compile time, or use dynamic memory allocation if the number of Rows and Columns are not yet known.

How can i effectively / correctly do that? (i already have a simple / naive idea):

const long Dynamic = -1;

template<typename T, long Rows, long Cols>
class Matrix {
    private:
        enum {
            kIsDynamicStorage = Rows == Dynamic || Cols == Dynamic
        };

        //?? conditional<is_dynamic_storage, vector<vector<T>>, T[Rows][Cols]> storage;
        // Use for fixed-size
        array<array<T, kIsDynamicStorage ? 0: Cols>, kIsDynamicStorage ? 0: Rows> storage;
        // Use for dynamic size
        vector<vector<T>> dynamic_storage;

    public:
        enum {
            kRowsAtCompileTime = Rows,
            kColsAtCompileTime = Cols
        };


        Matrix();
        // Use for dynamic size
        Matrix(size_t rows, size_t cols);
};

Is there a correct / better way to do this?

Aucun commentaire:

Enregistrer un commentaire