繁体   English   中英

C ++中的专用朋友功能

[英]Specialized friend function in C++

我有一个函数模板foo ,它必须根据template参数是实数还是复数来执行不同的计算。 无论如何,即使模板参数为std::complex<double> ,结果也将为实数,例如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
}; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM