C ++部分方法专业化

时间:2009-10-08 05:45:55

标签: c++ templates partial-classes

是否存在模板类方法的部分特化?

 template <class A, class B>
 class C
 {
  void foo();
 }

它不能像这样专门化它:

template <class A> void C<A, CObject>::foo() {};

任何帮助?

5 个答案:

答案 0 :(得分:12)

如果您已经有专门的课程,您可以在专业课程中提供foo的不同实施:

template<typename A, typename B>
class C
{
public:
    void foo() { cout << "default" << endl; };
};

template<typename A>
class C<A, CObject>
{
public:
  void foo() { cout << "CObject" << endl; };
};

要在Visual C ++ 2008中专门化成员函数,您也可以将其设为模板:

template<typename A, typename B>
class C
{
  template<typename T>
  void foo();

  template<>
  void foo<CObject>();
};

上述解决方案似乎只能在未来的C ++标准中使用(根据草案n2914 14.6.5.3/2)。

答案 1 :(得分:8)

我认为那里存在误解。

有两种模板:

  • 模板类
  • 模板方法

在您的示例中,您有一个模板类,当然包含一些方法。在这种情况下,您将必须专门化该类。

template <class A>
class C<A,CObject>
{
  void foo() { ... } // specialized code
};

您的示例中的问题相对简单:您定义特殊化C的方法foo,但此专业化事先从未声明

这里的问题是你必须完全专门化你的C类(从而复制大量数据)。有许多解决方法。

  • 继承(Composition?):执行基类中的所有常见工作,然后让C类继承并适当地进行专门化
  • 朋友:不要让'foo'方法成为C的成员,而是将其定义为朋友自由函数并仅专门使用此方法
  • 委托:让你的'foo'方法调用另一个方法'bar',这是一个免费的函数,并适当地专门化'bar'

在代码中给出了:

// 1- Inheritance
template <class A, class B>
class CBase
{
  // Everything that does not require specialization
};

template <class A, class B>
class C: public CBase<A,B>
         // depending on your need, consider using another inheritance
         // or even better, composition
{
  void foo(); // generic
};

template <class A>
class C<A,CObject> : public CBase<A,CObject>
{
  void foo(); // specialized
};

// 2- Friend
// note the change in signature:
// - now you need to pass the attributes to be changed
// - the last parameter helps differentiating the overload
//   as there is no specialization for functions
template <class A, class B> void foo(Arg1&, Arg2&, const B&);
template <class A> void foo(Arg1&, Arg2&, const CObject&);

template <class A, class B>
class C
{
  friend template <class, class> foo;
};

// 3- Delegation
// same signature as foo in (2)
template <class A, class B> void bar(Arg1&, Arg2&, const B&);
template <class A> void bar(Arg1&, Arg2&, const CObject&);

template <class A, class B>
class C
{
  void foo() { bar(member1, member2, B()); }
};

希望它澄清并帮助!

答案 2 :(得分:2)

不,要添加C ++ 0x中没有部分功能模板专用。

如上所述,关于功能模板,基本上做了两件事:

  • 默认模板参数可用;
  • 引入了可变参数模板。

与以前一样,变通办法应该用于“模拟”部分功能模板专业化。

答案 3 :(得分:1)

由于该类是模板,因此您需要专注于:

template <class A>
class C<A, CObject> 
{
   void foo() { ... }
}

答案 4 :(得分:0)

如果我没记错的话,你不能对功能进行部分模板专业化。不确定它是否包含在C ++ 0X

更新的 (等待确认)如注释中所述,可以在C ++ 0X中对函数进行部分模板特化。