In order to deal with vectors and fixed/dynamic allocation in some linear algebra problems, I built the following classes (which I would prefer not to modify ):
// Traits : n is the size of the vector, if -1 : dynamic allocation
template<typename RealType, int n = -1>
struct ClassAVectorTraits
{
typedef typename LinearAlgebraLibrary::FixedSizeVector<RealType, n> type;
};
template<typename RealType>
struct ClassAVectorTraits<T, -1>
{
typedef typename LinearAlgebraLibrary::DynamicSizeVector<RealType> type;
};
template<typename RealType>
struct ClassAVectorTraits<T, 1>
{
typedef typename RealType type;
};
// Implementation
template<typename RealType, int n = -1>
struct ClassA
{
typedef typename ClassAVectorTraits<RealType, n>::type vector;
void doSomething( const vector& vec )
{
...
}
};
Moreover I have an interface class (which I can modify) :
template<typename RealType, int n = -1>
struct UserClass
{
typedef typename ClassAVectorTraits<RealType, n>::type vector;
ClassA ca;
void doSomething( const vector& vec )
{
ca.doSomething( vec );
}
};
Now I want the user to be able to give STL vectors in input instead of LinearAlgebraLibrary vectors, so I did the following :
// A class to do automatic conversion
template<typename RealType, int n = -1>
struct Field : public ClassAVectorTraits<RealType,n>::type
{
// Constructor NOT explicit
Field( const std::vector<RealType>& vec )
{
// Copy vec into this (a LinearAlgebraLibrary vector)
}
}
template<typename RealType>
struct Field<RealType, 1> { }; // Can't derive from integral type : RealType !
// And to classes to tag the solution
template<typename RealType, int n>
struct USE_LINEAR_ALGEBRA_LIBRARY
{
typedef typename ClassAVectorTraits<RealType,n>::type vector;
};
template<typename RealType, int n>
struct USE_STL
{
typedef typename Field<RealType,n> vector;
};
And finally :
template<typename RealType, int n = -1, class VectorTag = USE_LINEAR_ALGEBRA_LIBRARY<RealType, n> >
struct UserClass
{
typedef typename VectorTag::vector vector;
ClassA ca;
void doSomething( const vector& vec )
{
ca.doSomething( vec );
}
};
And therefore, if we use the USE_STL tag, there is an automatic conversion :
UserClass<double, 2, USE_STL<double, 2> > userClass;
std::vector<double> vecSTL(2, 12.0);
userClass.doSomething( vecSTL ); // vecSTL is converted to LinearAlgebraLibrary::FixedSizeVector<double, 2>
My question : how can I deal with the n=1 case in which the vector type is an integral type. How can I define an implicit conversion between STL vector of double (size == 1) with a double ?
Any suggestions ? Thanks.
You don’t have to follow the scheme of generic template when you are about to specialize. Hope this helps: