当前位置:   article > 正文

C++_template(::type)_c++ ::type

c++ ::type

graph_tool中的::type

参考网址:C++ template typedef
graph_tool中使用结构体<xx(模板形参)>::type的含义就是用这个结构体指定一个type类型为type代替原来的复杂的类型。

    struct apply
    {
        typedef typename boost::graph_traits<Graph>::vertex_iterator type;
    };

    template <class Graph>
    static std::pair<typename apply<Graph>::type,
                     typename apply<Graph>::type>
    range(Graph& g)
    {
        return edges(g);
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

结构体有一些参数是固定的,这样可以少写几个参数,比如说下面的例子,最后用Vector<3>::type代替Matrix1<M.N>。这样做还有一个好处是,VectorMatrix1可以分开定义。如下面例子中Vector是一个模板结构体,而Matrix1是一个类。

example

使用typedef定义一个Vector,相当于一个(N,1)大小的矩阵。

typedef Matrix<N,1> Vector<N>;
  • 1

上面这个编译不通过。
要使用参考网址里面的这个:
首先定义一个Matrix1类。

template <size_t N>
using Vector = Matrix<N, 1>;
  • 1
  • 2

然后再定义一个结构体模板Vector:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};
  • 1
  • 2
  • 3
  • 4
  • 5

完整代码:

#include<iostream>
//#include<vector>

//typedef Matrix<N,1> Vector<N>;
template<size_t N, size_t M>
class Matrix1 {
    int a[N][M]={0};
    // 构造函数可以不要,编译能够通过。
    public:
    // 注意声明函数为公共函数!!!否则不可见。
    void init(int A[N][M]){
        for(int i=0;i<N;i++){
            // 注意数组是从0开始的,所以是M-1!!!
            a[i][M-1]=A[i][M-1];
        }

    }
};

template <size_t N>
struct Vector
{
    typedef Matrix1<N, 1> type;
};


int main(){
    // 
    Vector<3>::type a;
    int A[3][1]={{1},{2},{3}};
    int B[3][1]={1,2,3};
    a.init(B);
    for(int i=0;i<3;i++){
        std::cout<< 2-i <<" "<<B[2-i][0]<<std::endl;
        A[i][0]=B[2-i][0];
    }
    return 0;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号