使用模板类的别名

时间:2017-12-09 14:50:06

标签: c++ c++11 templates alias

我没有找到关于这个问题的任何答案: 我正在编写一个模板类DenseMatrix,在Matrix之前使用规范“密集”的必要性是因为这个类在层次结构中具有顶部的基本抽象类Matrix从中派生出SparseMatrix(从中派生出很多类表示稀疏矩阵的不同存储方式,如CRS,MCRS,BlockCSR ..) 现在,我在main函数中提供了使用简单名称矩阵实例化DenseMatrix类的对象的可能性(注意不是像抽象基类那样的Matrix),所以我记得在C中可能使用了

typdef struct {

} name ;

然后

name obj ; // instance of struct  

我希望在C ++类中获得相同的东西(面向C ++ 11) 这是直接在DenseMatrix类声明的标题中执行此操作的最佳方法? 附:在定义方法期间,我总是使用DenseMatrix ::而不是别名

编辑这里的示例,查看代码的结尾

# include "Matrix.H"

template <typename Type>
class DenseMatrix ;

template<typename U>
std::ostream& operator<<(std::ostream& os, const DenseMatrix<U>& m )



    template <typename Type>
    class DenseMatrix 
                               :     public Matrix<Type> 
    {


           template<typename U>
           friend std::ostream& operator<<(std::ostream& os, const DenseMatrix<U>& m );

    //--
    //
       public:

           constexpr DenseMatrix (std::initializer_list<std::vector<Type>> ) noexcept ;

           constexpr DenseMatrix (const std::string& );

     //       constexpr DenseMatrix (std::size_t , std::size_t);

           virtual  ~DenseMatrix() = default ;

           Type& operator()(const std::size_t , const std::size_t) noexcept override;

           const Type& operator()(const std::size_t , const std::size_t ) const noexcept override;

           void constexpr print () const noexcept override ;

           auto constexpr size1()const noexcept { return Rows ; }

           auto constexpr size2()const noexcept { return Cols ; }

           Type constexpr findValue(const std::size_t , const std::size_t ) const noexcept ;

       protected:

           std::vector<Type> data ;

           std::size_t Rows ;
           std::size_t Cols ;

           mutable Type dummy ;
    } ;
// here ------\/ -------
template <typename T>
using matrix<T> = DenseMatrix<T>

感谢@ R2RT这就是我要找的东西!的解决

1 个答案:

答案 0 :(得分:1)

如果我找到了你,那么你几乎就在这里,但你有一个<T>太多了:

template <typename T>
using matrix = DenseMatrix<T>;

它被称为模板别名

  

别名模板是一种模板,在专门化时,等同于将别名模板的模板参数替换为type-id

中的模板参数的结果。

http://en.cppreference.com/w/cpp/language/type_alias

相关问题