1

为了处理一些线性代数问题中的向量和固定/动态分配,我构建了以下类(我不想修改):

// 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 )
    {
      ...
    }
};

此外,我有一个接口类(我可以修改):

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 );
    }

};

现在我希望用户能够在输入中给出 STL 向量而不是 LinearAlgebraLibrary 向量,所以我做了以下操作:

// 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;
};

最后:

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 );
    }

};

因此,如果我们使用 USE_STL 标签,就会自动转换:

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>

我的问题:如何处理n=1向量类型是整数类型的情况。如何定义 double (size == 1) 的 STL 向量与 a 之间的隐式转换double

有什么建议么 ?谢谢。

4

1 回答 1

0

当您即将进行专业化时,您不必遵循通用模板的方案。希望这可以帮助:

template<typename RealType>
struct Field<RealType, 1> { 
   typename ClassAVectorTraits<RealType,1>::type value;
   operator ClassAVectorTraits<RealType,1>::type () const { return value; }
   Field(const std::vector<RealType>& vec) 
   {
       if (vec.size() == 1) value = vec[0];
       else throw runtime_error("wrong size");
   }
}; 
于 2012-06-24T07:33:22.663 回答