c++ - 为模板类使用别名

标签 c++ c++11 templates alias

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

typdef struct {

} name ;

然后

name obj ; // instance of struct  

我想获得相同的东西,但在 C++ 类中(面向 C++11) 这是直接在 DenseMatrix 类声明的 header 中执行此操作的最佳方法? 附言在定义方法的过程中,我总是使用 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,这正是我要找的! 已解决

最佳答案

如果我没猜错,那么你就快到了,但你有一个 <T>太多了:

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

这叫做模板别名

An alias template is a template which, when specialized, is equivalent to the result of substituting the template arguments of the alias template for the template parameters in the type-id

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

关于c++ - 为模板类使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47729783/

相关文章:

c++ - 在对象构造中使用 "="的影响

c++ - 具有可变构造函数的类模板;将参数存储到 std::vector< std::shared_ptr<>>

c++ - 获取最大的无符号整数类型

c++ - constexpr 未定义行为

c++ - 使用函数模板重载运算符

c++ - 如何使用模板类允许从 float 到 int 的赋值

c++ - 使用姐妹继承

python - 如何构建 Boost 和编译 Boost Python

c++ - Valgrind 报告 "Invalid free()/delete/delete[]"

c++ - 如何创建基类的单个实例