首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

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

2012-03-12 
VC8到GCC移植问题:模板类中的成员模板函数在全局模板函数中无法调用C/C++ code#include iostreamusing n

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 VC2005void 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 VC2005template <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》

热点排行