Create a class that can be converted to / from other libraries

I wrote a small stand-alone library (it depends only on the standard C ++ library), which has its own built-in three-dimensional vector class:

namespace mylibrary {

    struct Vector {
        double x, y, z;

        // and constructors
        // like:
        Vector(double x, double y, double z);

        // and operators
    };

}

It should interact with other code that creates / uses 3D vectors.

Now suppose another library that has:

namespace otherlibrary {
    struct Vector3 {

        // some different definition

        // And is still able to construct from 3 values
        Vector3(double x, double y, double z);
    };

    doSomething(const Vector3& point); // do something with the point
}

This other library may be a plugin API for a 3D modeling tool or a 3D engine. It also has a concept for a 3D vector, but it certainly differs from my library vector, although the semantics are identical. Think of the Python duck set: a type doesn't matter if it behaves as expected.

Question:

, Vector otherlibrary::doSomething()?

, :

otherlibrary::doSomething( mylibrary::Vector(...) );

, , Vector, , T "x, y, z" operator[], , . ?

EDIT:

, , 3D- . , , , , Eigen:: Vector3d , , Eigen.

:

:

struct Vector {
    using value_type = double;

    template<class T,
             class = typename enable_if<
                 is_constructible<T, value_type,value_type,value_type>::value
                 >::type>
    operator T() const
    {
        return T{x, y, z};
    }
};

enable_if ; Eigen - , .

+1
2

Vector.

operator otherlibrary::Vector3() const
{
    return otherlibrary::Vector3(x, y, z);
}

, .

, , . , ​​ , .

template<class T, U>
T ConvertVector3(const U& v)
{
    return T(v.x, v.y, v.z);
}

otherlibrary::doSomething(ConvertVector3<otherlibrary::Vector3>(mylibrary::Vector(x, y, z)));

: (

Experimental!! , . : , 3 ,

template<class T>
operator T() const
{
    return T(x, y, z);
}
+2

vector3, . - , "" .

, , std::array. , to_array(), . , array::data(), C.

(Protip: reinterpret_cast C-style std::array & , .)

0

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


All Articles