jeudi 26 janvier 2017

How to provide a common interface for creation of static and dynamic size vectors?

I have a lot of code that currently works with dynamic size vectors (such as std::vector, Eigen::VectorXd, ...) and I would like it to work also with static size vectors (such as std::array, Eigen::Vector3d, ...). My code is templatized with respect to TVector in such a way that it assumes that TVector has just size and operator[]. But the big problem is construction.

There are no common grounds when it comes to construction of both static and dynamic vectors. I have decided to replace all calls to the constructor of TVector by the following hypothetical function:

template <typename TVector>
TVector createVector(std::size_t sizeAtInitialization)
{
    if (TVector has constructor taking an integral type)
        return TVector(sizeAtInitialization);
    else
        return TVector(); // sizeAtInitialization ignored
}

Such that a generic call to createVector<TVector> will become createVector<std::vector<double>>(3) or createVector<std::array<double, 3>>(3).

std::is_default_constructible will not help me here, since both vector types are default constructible.

However, I am not sure that such a thing is even possible.

I have studied the static if here and member function detection here. It all seems extremely complicated and since the static_if uses lambdas which must return to an intermediate result, which must already be constructed, I am not sure it leads anywhere.

Aucun commentaire:

Enregistrer un commentaire