I have simple codes for templated and non-templated versions of the same class. Each class has the same data structure (Point
). The compiling problem happens for the templated class when defining the function with the structure Point
externally. I compiled the codes with Visual Studio.
//non-templated class is defined without a compiling error.
class Geometry1 {
public:
struct Point
{
double x = 1, y = 2, z = 3;
};
public:
Point GetAPoint()//Function is defined internally
{
Point test;
return test;
}
Point GetAnotherPoint();//Function will be defined externally
};
Geometry1::Point Geometry1::GetAnotherPoint()//This externally defined function is fine with Point
{
Point test;
return test;
}
//Now a templated version of Geometry1 is defined. Compiling error happens!!!
template<typename type>
class Geometry2{
public:
struct Point
{
type x=1, y=2, z=3;
};
public:
Point GetAPoint()//No compiling error
{
Point test;
return test;
}
Point GetAnotherPoint();//Function will be defined externally WITH compiling error
};
template<class type>
Geometry2<type>::Point Geometry2<type>::GetAnotherPoint()//This externally defined function causes compiling error with Point: Error C2061 syntax error: identifier 'Point'
{
Point test;
return test;
}
int main()
{
Geometry1 geo1;//There is compiling error for this class
Geometry1::Point p1 = geo1.GetAnotherPoint();
Geometry2<double> geo2;//Compiling error happens for this class
Geometry2<double>::Point p2 = geo2.GetAPoint();
}
Complete error messages are:
Severity Code Description Project File Line Suppression State
Error C2061 syntax error: identifier 'Point' TestClasstypedef TestClasstypedef.cpp 51
Error C2143 syntax error: missing ';' before '{' TestClasstypedef TestClasstypedef.cpp 52
Error C2447 '{': missing function header (old-style formal list?) TestClasstypedef TestClasstypedef.cpp 52
Error C2065 'geo1': undeclared identifier TestClasstypedef TestClasstypedef.cpp 60
Error C2065 'geo2': undeclared identifier TestClasstypedef TestClasstypedef.cpp 63
I found that if Geometry2::GetAnotherPoint()
is defined internally like Geometry2::GetAPoint()
, the problem will be completely solved.
Could anyone help me to figure out my mistake? Thank you in advance!