C++中的专用朋友功能

Specialized friend function in C++

本文关键字:朋友 功能 专用 C++      更新时间:2023-10-16

我有一个函数模板foo,它必须根据模板参数是实数还是复数执行不同的计算。在任何情况下,结果都将是一个实数,例如 double,即使模板参数是std::complex<double>。因此,我的函数如下所示:

template <class S>
struct RealType
{
  typedef S type;
};
template <class S>
struct RealType<std::complex<S> >
{
  typedef S type;
};
template <class S>
class C;
template <class S>
typename RealType<S>::type foo(C<S> &c);
template <class S>
typename RealType<std::complex<S> >::type foo(C<std::complex<S> > &c);

现在foo一定是类C的友元函数,所以我做了如下声明:

template <class S>
class C
{
  friend typename RealType<S>::type foo(C<S> &c);
  // ...
};

但是,当我实例化C<std::complex<double> >编译器说foo无法访问c的私有成员。它适用于C<double>.是否有任何解决方案(适用于C++98)?我知道foo不能成为C的成员,因为这会阻止部分专业化。

顺便说一句:这真的是一种专业化吗?两个版本的foo签名看起来相同,但实际上,当插入实际类型时,它们会有所不同。

确保class C在声明foo声明foo朋友。

为此,您可能需要使用前向声明:

template <class S> class C;
// foo declarations here
template <class S> class C 
{ 
    template<class X> friend typename RealType<X>::type foo(C<X> &c); // friend the template
    friend typename RealType<S>::type foo<>(C &c); // friend the specialization
};