C++中的专用朋友功能
Specialized friend function in C++
我有一个函数模板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
};
相关文章:
- 类似虚拟的朋友功能?
- 朋友功能声明中的错误C
- 朋友功能不起作用(语法错误)
- Forward宣布了Singleton班级,并带有Freshial声明的朋友功能
- 我的朋友功能无法访问私人变量
- 我正在尝试使用朋友功能,但我无法访问第二类的私人数据成员
- 朋友功能可访问性问题
- 防止朋友功能访问班级的私人会员
- 朋友功能声明为会员函数
- 朋友功能无法访问私有成员变量
- 朋友功能是否继承?为什么基类朋友功能在派生的类对象上工作
- 使用模板独立enable_if时,链接器错误带有模板的朋友功能
- 朋友功能程序未产生主要功能中所需的值
- 朋友功能和继承在CPP中
- 使用朋友功能和正常公共功能时的行为差异
- 非成员的朋友功能始终是内联的
- 朋友功能模板查找
- 课堂定义的朋友功能的范围
- 模板类的朋友功能:C
- 模板类的朋友功能需要访问会员类型