具有模板成员的模板类,检查实例化

时间:2013-03-07 22:29:35

标签: c++ debugging templates compiler-errors

我有一个关于模板类的C ++项目(库)(不同类型的矩阵,每种类型都有不同的容器,容器的value_type不同 - 矢量等相同)。

每个模板类都有模板成员,因为

DenseRectangularMatrix<std::vector<long double>> //type-container-value_type

必须能够(如果是5x5)乘以

DenseSymmetricMatrix<std::array<float,15>> //(5x5) type-container-value_type

我的问题是编译实例化。 由于存在许多模板关系,因此很难实例化所有可能的情况,不仅用于测试/调试,还要检查编译器是否发生错误。

有没有想过这个?

1 个答案:

答案 0 :(得分:1)

解决此类问题的C方法可能是使用宏和脚本来简化所有可能性的生成。但是,我们在C ++中编码,所以让我们用模板替换宏。毕竟,这些是基本类型的宏。

所以我的想法是在更基本的类型中分解你的类型,并使用模板来构建它们。

enum {
    RECTANGULAR,
    SYMMETRIC,
} DimKind;

enum {
    DENSE,
    PARSE
} Density;

enum {
    STD_ARRAY,
    STD_VECTOR
} ContainerType;

enum {
    FLOAT,
    DOUBLE
} CoordType;

template <CoordType CT>
struct coord_def {
};

struct coord_def<FLOAT>{
    typedef float type;
};

struct coord_def<DOUBLE> {
    typedef double type;
};


template <ContainerType Cont, CoordType Coord, int Dimension>
struct container_def {
};

template <CoordType Coord, int Dim>
struct container_def<STD_ARRAY, Coord, Dim> {
    typedef std::array<Coord,Dim> type;
    static const int dim = Dim;
    // add any other helper function needed to build the test case for that particular
    // container
};

template <CoordType Coord, int Dim>
struct container_def<STD_VECTOR, Coord, Dim> {
    typedef std::vector<Coord> type;
    static const int dim = Dim;
};

template <Density D, DimKind DK, ContainerType Cont, 
                  CoordType Coord, int XDim, int YDim>
struct TestMatrix {
};

// here specialize the above according to the parameters
// you may need to include helper function to build an instance using the template
// parameters (dimension comesto mind)

然后,您必须定义要测试的操作类型。它们当然可以分为矩阵与分量,矩阵与矢量,矩阵与矩阵。

enum { 
    // matrix ops list
} MatrixOp;

template <MatrixOp Op, typename M1, typename M2, typename Ret>
Ret binary_op(M1 m1, M2 m2);

 // overload for specific functions

template <MatrixOp Op,
                  ContainerType Cont1, ContainerType Cont2
                   CoordType Coord1, CoordType Coord2,
                   int XDim1, int YDim1, int XDim2, int YDim2,
                   Denstity D1, Density D2,
                   DimKind K1, DimKind K2>
struct test_op {
    typedef TestMatrix<...>::type M1;
    typedef TestMatrix<...>::type M2;
    void test(M1 m1, M2 m2){
         binary_op<MatrixOp,M1,M2>(m1, m2);
     }
};

接下来,您的矩阵之间肯定存在代数关系,您可以将其编码为模板,并用于测试。

例如,DenseSymmetricMatrix模板的参数似乎指定了静态大小的容器类型。对于这样的* n矩阵,数组的维度必须是n *(n + 1)/ 2另一方面,DenseRectangularMatrix似乎在运行时定义了它的维度。但由于您具有上述维度的关系,因此您可以轻松地将两个测试用例编写为模板:一个用于构建两个具有匹配维度的矩阵,另一个用于具有不匹配维度的矩阵。

最后一步是产生所有可能性。一个简单的脚本通过所有的枚举&#39;轮次中的值应该有助于产生所有可能的测试。

我相信你也可以使用现有的单元测试框架(比如增强版)来构建你的测试。

相关问题