是什么导致模板化 class 的编译错误?

What causes compiling error with templated class?

我有相同 class 的模板化和非模板化版本的简单代码。每个 class 具有相同的数据结构 (Point)。在外部定义结构为Point的函数时,模板化的class会出现编译问题。我用 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();
}

完整的错误信息是:

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  

我发现如果像Geometry2::GetAPoint()那样在内部定义Geometry2::GetAnotherPoint(),问题就彻底解决了

谁能帮我找出我的错误? 提前致谢!

问题Geometry2<type>::Point是一个从属限定名。此外,这个从属名称是 type 所以你需要告诉编译器你可以通过在 Geometry2<type>::Point 之前添加关键字 typename 来做到这一点。所以修改后的代码看起来像:

template<class type>
typename Geometry2<type>::Point Geometry2<type>::GetAnotherPoint()//note the keyword typename here
{
    Point test;
    return test;
}