【发布时间】: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<std::complex<double> > 时,编译器说foo 不能访问c 的私有成员。它适用于C<double>。有没有解决方案(适用于 C++98)?我知道foo 不能是C 的成员,因为这会阻止部分专业化。
顺便说一句:这真的是专业吗? foo 的两个版本的签名看起来一样,但实际上插入真实类型时它们的签名有些不同。
【问题讨论】:
-
IIRC 你需要一些类似的东西:
template<class U> friend typename RealType<U>::type foo(C<U> &c);
标签: c++ templates template-specialization specialization partial-specialization