[英]Specialized friend function in C++
I have a function template foo
that has to perform different computations depending on whether the template parameter is a real or a complex number. 我有一个函数模板
foo
,它必须根据template参数是实数还是复数来执行不同的计算。 In any case, the result will be a real number, eg double
, even if the template parameter is std::complex<double>
. 无论如何,即使模板参数为
std::complex<double>
,结果也将为实数,例如double
。 Therefore, my function looks as follows: 因此,我的函数如下所示:
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);
Now foo
must be a friend function of the class C
, so I made the following declaration: 现在
foo
必须是C
类的朋友函数,因此我做了以下声明:
template <class S>
class C
{
friend typename RealType<S>::type foo(C<S> &c);
// ...
};
However, when I instantiate C<std::complex<double> >
the compiler says that foo
cannot access the private members of c
. 但是,当我实例化
C<std::complex<double> >
,编译器说foo
无法访问c
的私有成员。 It works fine for C<double>
. 它对于
C<double>
可以正常工作。 Is there any solution to this (that works with C++98)? 有什么解决方案(适用于C ++ 98)吗? I understand that
foo
cannot be a member of C
, as this will prevent the partial specialization. 我知道
foo
不能是C
的成员,因为这将阻止部分专业化。
BTW: Is this really a specialization? 顺便说一句:这真的是专业吗? The signatures of both versions of
foo
look the same, but in fact they are somewhat different when the real types are plugged in. 两种版本的
foo
的签名看起来相同,但实际上,插入实类型时它们有些不同。
Make sure that class C
declares foo
a friend after foo
has been declared. 确保
class C
声明foo
经朋友foo
已申报。
You may need to use forward declarations for that: 您可能需要为此使用前向声明:
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.