对unique_ptr模板使用typedef
using typedef for unique_ptr template
编译以下代码:
matrix.h before template
template<typename T>
class Matrix
{
public:
//...
unique_ptr<Matrix<T>> Test() const;
};
matrix.cpp
template<typename T>
unique_ptr<Matrix<T>> Matrix<T>::Test() const
{
unique_ptr<Matrix<T>> a{ new Matrix<T>{ 1, 1 } };
return std::move(a);
}
我想使用一个typedef (using)来缩短的东西,因为我认为它会更可读,但我的改变导致错误。以下是相关的修改。
matrix.h after template
template<typename T>
class Matrix
{
public:
//...
MatrixUniq<T> Test() const;
};
template<class T> using MatrixUniq = unique_ptr<Matrix<T>>;
模板后的matrix.cpp
template<typename T>
MatrixUniq<T> Matrix<T>::Test() const
{
MatrixUniq<T> a{ new Matrix<T>{ 1, 1 } };
return std::move(a);
}
在做了这些修改之后编译会使vc++编译器崩溃两次,但也会产生一些错误:
Error C2143 syntax error: missing ';' before '<'
Error C4430 missing type specifier - int assumed.
Error C2238 unexpected token(s) preceding ';'
Error C1903 unable to recover from previous error(s);
我的typedef实现有什么问题?谢谢。
编辑:我正在使用VS2015。我正在构建一个静态库。在matrix.cpp的底部我有:
template class VMatrix<double>;
您在定义MatrixUniq<T>
别名之前使用它。
将using
移动到类中:
template<typename T>
class Matrix
{
public:
template<class U> using MatrixUniq = std::unique_ptr<Matrix<U>>;
MatrixUniq<T> Test() const;
};
并相应地更改定义:
template<typename T>
Matrix<T>::MatrixUniq<T> Matrix<T>::Test() const
{
return MatrixUniq<T>{ new Matrix<T>{ 1, 1 } };
}
或者,如果您希望在全局命名空间中使用它,则在类的前向声明之后的类定义之前定义它:
template<typename T>
class Matrix;
template<class T> using MatrixUniq = std::unique_ptr<Matrix<T>>;
template<typename T>
class Matrix
{
public:
//...
MatrixUniq<T> Test() const;
};
当返回局部变量时,您也不需要显式地执行std::move
。默认情况下,返回的局部变量会自动移动。
try this:
template<typename T>
class Matrix
{
public:
using unique_ptr_type = std::unique_ptr<Matrix>;
//...
unique_ptr_type Test() const;
};
template<class T> using MatrixUniq = typename Matrix<T>::unique_ptr_type;
template<typename T>
typename Matrix<T>::unique_ptr_type Matrix<T>::Test() const
{
return unique_ptr_type(new Matrix());
}
始终确保在将要使用它的代码上方声明模板。
还有这个片段:
template<class T> using MatrixUniq = unique_ptr<Matrix<T>>;
might not be a correct implementation.
Here's how you can declare a type definition in c++.
typedef <type> <var_name>
下面是另一个使用"别名模板"的例子
template<typename T>
using MyVector = std::vector<T, MyCustomAllocator<T>>;
剩下的代码供您调试。
查看此处的相关讨论:
如何定义模板类?
相关文章:
- C++:TypeDef使用元组
- 为什么 std::unique 不调用 std::sort?
- 有没有一种方法可以通过"typedef"为重新定义的基本类型定义特征和强制转换运算符
- 为什么在使用typedef时类推导指南会失败
- 尝试根据类中 typedef 的存在来专门化模板函数
- 如何重新定义MPI_FLOAT,MPI_DOUBLE以 typedef 的方式
- typedef 枚举和枚举类有什么区别?
- 在类模板中使用 typedef 时出错
- 模板类中的 typedef 语句
- 在 typedef 内部使用 const 关键字和在 typedef 外部使用 const 关键字之间有区别吗?
- 如何将成员函数作为回调参数传递给需要"typedef-ed"自由函数指针的函数?
- 生成"unique"矩阵
- C++中"typedef"、"using"、"namespace"和"using namespace"有什么区别?
- 向前声明指向类的 typedef 指针
- 使用typedef'ed返回类型声明友元函数时出现编译器错误
- 如何创建 typedef 结构的前向声明
- 从 Typedef 数据类型中删除常量
- typedef vector size_type in header file
- typedef 别名的析构函数
- 如何使用 typedef 创建多个数组?