VC8到GCC移植有关问题:模板类中的成员模板函数在全局模板函数中无法调用

VC8到GCC移植问题:模板类中的成员模板函数在全局模板函数中无法调用
C/C++ code


#include <iostream>
using namespace std;

struct XYZ
{
    int    x;
};

template <class S>
class SomeTemplateClass
{
public:

    template <class T>
    T* SomeTemplateMemberFunc(void)
    {
        return (T*)(data);
    }

    void* data;
};

// OK on g++, OK on VC2005
void SomeNonTemplateGlobalFunc(const XYZ& data)
{
        SomeTemplateClass<XYZ> v;
        v.data = (void*)&(data.x);
        int* result = v.SomeTemplateMemberFunc<int>();
        cout << "In SomeNonTemplateGlobalFunc()\n"
            << "data = " << *result << endl;
}

// Error on g++, OK on VC2005
template <class S>
void SomeTemplateGlobalFunc(const S& data)
{
    SomeTemplateClass<S> v;
    v.data = (void*)&(data.x);
    int* result = v.SomeTemplateMemberFunc<int>();
    cout << "In SomeTemplateGlobalFunc()\n"
        << "data = " << *result << endl;
}



int main()
{
    cout << "Begin..." << endl;
    
    XYZ x;
    x.x = 666;

    SomeNonTemplateGlobalFunc(x);    // OK on g++, OK on VC2005
    SomeTemplateGlobalFunc(x);        // Error on g++, OK on VC2005
    

    cout << "End..." << endl;
    return 0;
}




上述代码在VC2005中OK,但在gcc(g++)中出错:
test.cpp: In function ‘void SomeTemplateGlobalFunc(const S&)’:
test.cpp:39: error: expected primary-expression before ‘int’
test.cpp:39: error: expected ‘,’ or ‘;’ before ‘int’

请高手点拨


------解决方案--------------------
召唤 taodm
------解决方案--------------------
#include <iostream>
using namespace std;

struct XYZ
{
int x;
};

template <class S>
class SomeTemplateClass
{
public:

template <class T>
T* SomeTemplateMemberFunc(void)
{
return (T*)(data);
}

void* data;
};

// OK on g++, OK on VC2005
void SomeNonTemplateGlobalFunc(const XYZ& data)
{
SomeTemplateClass<XYZ> v;
v.data = (void*)&(data.x);
int* result = v.SomeTemplateMemberFunc<int>();
cout << "In SomeNonTemplateGlobalFunc()\n"
<< "data = " << *result << endl;
}

// Error on g++, OK on VC2005
template <class S>
void SomeTemplateGlobalFunc(const S& data)
{
SomeTemplateClass<S> v;
v.data = (void*)&(data.x);
int* result = v.template SomeTemplateMemberFunc<int>();
cout << "In SomeTemplateGlobalFunc()\n"
<< "data = " << *result << endl;
}



int main()
{
cout << "Begin..." << endl;

XYZ x;
x.x = 666;

SomeNonTemplateGlobalFunc(x); // OK on g++, OK on VC2005
SomeTemplateGlobalFunc(x); // Error on g++, OK on VC2005


cout << "End..." << endl;
return 0;
}
------解决方案--------------------
如果精力足够旺盛,看《C++ templates》