模板与名字空间

OOPhaisky 2006-07-15 07:55:32
------------------------------------------------------------------------------------
问题:
一个模板在名字空间中定义,[不在名字空间中进行模板特化声明,直接在名字空间外面定义模板特化]这种情况允许么?(对于非模板实体,不可以[不在名字空间中首先声明就在名字空间外面加以定义],这个想必大家都知道)
------------------------------------------------------------------------------------
例子:
1.类模板:
namespace ns{
template <class T>//类模板在名字空间中定义
class foo{
public:
void test(T a){
cout << "aaaa:" << a << endl;
}
};
}
template<>//类模板显式特化,未在名字空间ns中声明
class ns::foo<int>{
public:
void dddd(){
cout << "dddd" << endl;
}
};
结果:vs2005成功,g++失败。

2.函数模板:
namespace ns{
template <class T>//函数模板在名字空间中定义
void test(T a){
cout << a << endl;
}
}
template<>//函数模板显式特化,未在名字空间ns中声明
void ns::test(int){
cout << "int" << endl;
}
结果:vs2005成功,g++失败。
------------------------------------------------------------------------------------
望高手解答,谢谢。
...全文
157 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
triace_zhang 2006-07-15
  • 打赏
  • 举报
回复
ISO/IEC 14882:1998(E) -- C++ -- Templates
14.7.3 [temp.expl.spec]

2 An explicit specialization must be declared in the namespace of which
it is a member, or, for class members, in the namespace of which the
class is a member. Such a declaration may also be a definition. If

the declaration is not a definition, the specialization may be defined
later in the namespace in which the explicit specialization was
declared, or in a namespace that encloses the one in which the
explicit specialization was declared.
6 A template explicit specialization is in the scope of the namespace in
which the template was defined. [Example:

namespace N {
template<class T> class X { /* ... */ };
template<class T> class Y { /* ... */ };

template<> class X<int> { /* ... */ }; // ok: specialization
// in same namespace
template<> class Y<double>; // forward declare intent to
// specialize for double
}

template<> class N::Y<double> { /* ... */ }; // ok: specialization
// in same namespace
--end example]
OOPhaisky 2006-07-15
  • 打赏
  • 举报
回复
标准对此有相应说明么?
chenhu_doc 2006-07-15
  • 打赏
  • 举报
回复
相对地说....
chenhu_doc 2006-07-15
  • 打赏
  • 举报
回复
还是按照标准写,通用!
gushenghua 2006-07-15
  • 打赏
  • 举报
回复
俺来说句废话,这个得查C++标准,如果标准没做说明,那么写程序得避开这个问题

64,671

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧