无法使基于模板的c++代码编译:在类之前需要typename

Unable to Make Template Based C++ Code Compile: Needed typename before Class

本文关键字:typename 编译 于模板 代码 c++      更新时间:2023-10-16
using namespace std;
using namespace Eigen;
template<int x>
class MyClass{
    typedef Matrix<float,x,x> MyMatrix;
    MyClass();
    MyMatrix getMatrix();
};
template<int x>
MyClass<x>::MyClass(){
    int y =  x+1;
    MyMatrix m;
    MyClass::MyMatrix mx;
}
template<int x>
MyClass<int x>::MyMatrix getMatrix(){
    MyMatrix m;
    return m;
}

我有下面的代码。不幸的是,最后一个声明不能编译(getMatrix),我得到一个错误,说我需要MyCLass::MyMatrix之前的类型名,因为MyCLass是一个依赖作用域

改成:

template<int x>
typename MyClass<x>::MyMatrix MyClass<x>::getMatrix(){
    MyClass<x>::MyMatrix mx;
    return mx;
}

仍然没有编译并给出相同的错误。还将它们设为public

你的代码中有很多错误。让我们一个一个地修复它们:

template<int x>
MyClass<x>::MyClass(){
    int y = x + 1;
    MyMatrix m;
    MyClass::MyMatrix mx;
}

在这里,甚至很难理解你在这里试图做什么。为什么会有y ?为什么你试图用不同的方式使用同一个类?下面是修复后的样子:

template<int x>
MyClass<x>::MyClass(){
    MyMatrix m;
    MyMatrix mx;
}

两个MyMatrix指的是同一个,即您在MyClass中声明的那个。


现在,这段代码:
template<int x>
MyClass<int x>::MyMatrix getMatrix(){
    MyMatrix m;
    return m;
}

这里的语法错误。解决这个问题的方法就是查看上面的代码,然后告诉编译器让你做什么:

template<int x>
//               v----- Here!
typename MyClass<x>::MyMatrix getMatrix(){
//                   ^--- Dependent name here. Matrix is a type that depends
//                        on the parameter `x`. You must put typename to
//                        tell the compiler that it's a type
    MyMatrix m;
    return m;
}

为什么在使用变量时要指定它的类型?

我看没有其他问题