【问题标题】:Specialized friend function in C++C++ 中的特殊友元函数
【发布时间】:2016-01-14 15:17:12
【问题描述】:

我有一个函数模板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&lt;std::complex&lt;double&gt; &gt; 时,编译器说foo 不能访问c 的私有成员。它适用于C&lt;double&gt;。有没有解决方案(适用于 C++98)?我知道foo 不能是C 的成员,因为这会阻止部分专业化。

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

【问题讨论】:

  • IIRC 你需要一些类似的东西:template&lt;class U&gt; friend typename RealType&lt;U&gt;::type foo(C&lt;U&gt; &amp;c);

标签: c++ templates template-specialization specialization partial-specialization


【解决方案1】:

确保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
}; 

【讨论】:

  • 谢谢,但我的代码就是这种情况,就像上面的例子一样。
  • 你是对的,你的代码实际上解决了问题。我太专注于前向声明,所以我没有看到您以不同的方式声明友元函数。另外,我的真实代码有更多的模板参数,但现在它可以工作了。非常感谢。
  • 注:如引用代码所示,template &lt;class X&gt; 的行似乎是不必要的。我想我将不得不再次检查 &lt;&gt; 到底做了什么。
  • @cthl 我在评论中提到了这两种不同语法的作用。
猜你喜欢
  • 1970-01-01
  • 2018-08-11
  • 2018-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多