C++博客 :: 首页 ::  :: 联系 ::  :: 管理

g++的一个bug?

Posted on 2006-10-12 16:28 chenger 阅读(3122) 评论(4)  编辑 收藏 引用 所属分类: Programming Stuff
今天写代码的时候,发现g++好像不支持模板成员函数的全特化。看代码:

class A
{
public:
    template
<typename T>
    T f(T val);

    template <>
    int
f<int>(int val);
};

我用的是g++ 3.4.2 mingw版本。编译上面这段代码时,错误信息如下:

5: error: invalid explicit specialization before '>' token
5: error: explicit specialization in non-namespace scope `class A'

如果把f的定义放到全局作用域中,就不会出错。而上面这段代码在VC++ 8.0下可以编译通过。运行起来也没有问题。别的编译器我没有试过。

Update:多谢周星星的指点,比较“常规”的写法如下:

class A
{
public:
    template <typename T>
    T f(T val);
};


template
<typename T>
T A::f(T val)
{
    // ...
}

template <>
int
A::f<int>(int val)
{
    //...
}


这种写法就没有任何问题(在g++ 3.4.2和VC++ 8.0下均表现正常)。至于为什么前面的写法导致g++下报错,还不是很清楚。

Feedback

# re: g++的一个bug?  回复  更多评论   

2006-10-13 05:36 by happia
我这里也差不多
#include <iostream>
using namespace std;

class A
{
public:
template <typename T>
T f(T val);
template <>
int f(int val);
};

[root@localhost soft]# g++ testtem.cpp
testtem.cpp:9: 错误:显式特例化出现在非命名空间作用域 ‘class A’ 中
testtem.cpp:10: 错误:‘f’ 不是一个模板函数

gcc 版本 4.1.0 20060304 (Red Hat 4.1.0-3)

# re: g++的一个bug?  回复  更多评论   

2006-10-13 11:17 by 周星星
看看
http://blog.vckbase.com/bruceteen/archive/2006/10/13/22750.html

# re: g++的一个bug?  回复  更多评论   

2007-02-11 13:56 by zade
According to the Standard, template specializations can only be declared in namespace scope

http://gcc.gnu.org/ml/gcc/1998-09/msg00985.html

# re: g++的一个bug?[未登录]  回复  更多评论   

2012-07-05 17:38 by flash
您好, 我也遇到這個問題, 但我是想要
struct A
{
template<typename T,typename T1>
void f( T val, T1 val1 );
};
template<typename T,typename T1>
void A::f( T val, T1 val1 ) const
{
std::cout << "type" << std::endl;
}
template<>
void A::f<int,typename T1>( int val, T1 val1 ) const
{
std::cout << "int" << std::endl;
}

win32 VC++ 會出現 cannot convert 1 from T1 to T1 錯誤

這種寫法該如何解決?

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理