c++ - 将 typedef 用于 unique_ptr 模板

标签 c++ templates

编译以下代码。

模板前的matrix.h

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(使用)来缩短内容,因为我认为它更具可读性,但我的更改会导致错误。以下是相关更改。

模板后的matrix.h

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返回局部变量时。默认情况下,返回的局部变量会自动移动。

关于c++ - 将 typedef 用于 unique_ptr 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31897333/

相关文章:

c++ - 如何将路径拆分为单独的字符串?

c++ - 打印给定类型名称的模板

c++ - 将虚拟假锁与 std::condition_variable_any 一起使用是否安全?

c++ - 在 C++ 中扩展后将 header 绑定(bind)到实现

c++ - 关于 Arduino Uno 的程序帮助

java vs C++ 通过引用传递

C++ - 使用带函数的模板时出现错误 'undefined reference'

c++ - 是否可以访问 C++ 模板模板常量参数?

c++ 异常类继承到模板类

c++ - 从派生类调用时推断 'this' 指针类型?