powerdog powerdog - 1 month ago 8
C++ Question

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

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;
}


I have the following code. Unfortuantely, the last decalration cannot compile (getMatrix) and I get an error saying that I need a typename before MyCLass::MyMatrix because MyClass is a dependant scope

Changed it to :

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


It is still not compiling and giving the same error. Also made them public

Answer

There are many errors in your code. Let's fix them one by one:

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

Here it's really hard to even understand what you are trying to do here. Why is there y? And why are you trying to use the same class differently? Here's what it look like when fixed:

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

Both MyMatrix refers to the same one, the one you declared in MyClass.


Now, this piece of code:

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

The syntax is wrong here. The solution how to fix this is simply by looking at your code just above, and tell the what the compiler told you to do:

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;
}

Why would you specify the type of a variable when you use it?

I see no other problems.