专门化模板类的模板化成员 [英] Specializing a templated member of a template class

查看:62
本文介绍了专门化模板类的模板化成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

模板化类中的模板化成员函数的专业化





template <class T>    
class MyClass
{
   template <int N>
   void func() {printf("unspecialized\n");}
};
template<class T>
template<>
MyClass<T>::func<0>()
{
   printf("specialzied\n");
}

这不起作用。可以专门化模板类的模板方法吗?

This does not work. Is it possible to specialize a template method of an template class?

推荐答案

它不能按要求完成。由于某些原因(我不确定其原理), explicit (即 full )仅在封闭类也显式地时才允许成员模板的专业化。 (即完全)专门。语言标准中明确说明了此要求(请参见C ++ 98,C ++ 03中的14.7.3 / 18和C ++ 11中的14.7.3 / 16)。

It cannot be done as requested. For some reason (I'm not sure about the rationale) explicit (i.e full) specialization of a member template is only allowed when the enclosing class is also explicitly (i.e fully) specialized. This requirement is explicitly spelled out in the language standard (see 14.7.3/18 in C++98, C++03 and 14.7.3/16 in C++11).

同时,允许成员 class 模板的 partial 专业化,在许多情况下,可以将其用作替代方法(尽管很丑陋)。但是,显然,它仅适用于成员 class 模板。当涉及成员 function 模板时,必须使用替代解决方案。

At the same time, partial specializations of member class templates are allowed, which in many cases can be used as a workaround (albeit an ugly one). But, obviously, it is only applicable to member class templates. When it comes to member function templates, an alternative solution has to be used.

例如,一种可能的解决方法是将调用委派给模板类的静态成员并对其进行专门化处理(通常建议采用比对功能模板进行专门化处理更好的主意 http: //www.gotw.ca/publications/mill17.htm

For example, a possible workaround is to delegate the call to a static member of a template class and specialize the class instead (which is often recommended as a better idea than specialization of function templates http://www.gotw.ca/publications/mill17.htm)

template <class T>    
class MyClass
{
   template <int N, typename DUMMY = void> struct Func {
     static void func() { printf("unspecialized\n"); }
   };

   template <typename DUMMY> struct Func<0, DUMMY> {
     static void func() { printf("specialized\n"); }
   };

   template <int N> void func() { Func<N>::func(); }
};

这篇关于专门化模板类的模板化成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆