我正在尝试移植一些Visual C ++(VS2005)代码,以便它可以在VS2005和C ++ Builder XE下编译。下面的代码在VS2005下编译得很好但在C ++ Builder XE下,我得到以下错误:
[BCC32错误] time_stamp.h(49):E2327运算符可能没有默认参数值
以下是有问题的代码:(time_stamp.h)
template<typename counter_type>
class time_stamp
{
typedef time_span<counter_type> time_span_type;
typedef typename counter_type::value_type value_type;
public:
/* some code removed for sake of this post, next line is the one causing the error */
friend time_span<counter_type> operator-(const time_stamp<counter_type> &first, const time_stamp<counter_type> &second)
{
return time_span<counter_type>(first.m_stamp - second.m_stamp);
}
private:
value_type m_stamp;
}
time_span模板如下(time_span.h):
template<typename counter_type>
class time_span
{
public:
// TYPES
typedef counter_type counter_type;
typedef typename counter_type::value_type value_type;
/* rest removed for sake of this post */
}
C ++ Builder编译器似乎不喜欢该行: 朋友time_span operator-(const time_stamp&amp; first,const time_stamp&amp; second)
我是模板的新手,这种语法让我失望,或者至少是我无法理解的编译器错误。对我来说,尽管编译器这么说,但似乎没有默认的参数值。我正在将错误消息解释为const time_stamp&amp;当它看起来像是传递类型为time_stamp的引用时是一个默认值。
感谢阅读&amp;回复。非常感谢帮助理解和修复。
---编辑:
如果我重新构建上面的调用,如下所示:
friend time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) );
在类定义之外,我描述了函数:
template<typename counter_type>
time_span<counter_type> operator-( (const time_stamp<counter_type>& first, const time_stamp<counter_type>& second) )
{
return time_span<counter_type>(first.m_stamp-second.m_stamp);
}
然后我收到此错误:
[BCC32错误] time_stamp.hpp(56):E2082' - (int(*)(const time_stamp&amp;,const time_stamp&amp;))'必须是成员函数或具有类类型的参数
答案 0 :(得分:1)
[替换我以前的答案!]
这可能与http://www.parashift.com/c++-faq/templates.html#faq-35.16有关。
由于您要定义的函数实际上是一个模板函数(它取决于counter_type
),您应该在friend
声明之前声明它,然后声明一个函数模板实例化为friend
:
// time_stamp.h
#include "time_span.h"
template<typename counter_type> class time_stamp;
template<typename counter_type> time_span<counter_type> operator-(
const time_stamp<counter_type>&, const time_stamp<counter_type>& );
template<typename counter_type>
class time_stamp
{
//...
friend time_span<counter_type> operator- <> (
const time_stamp<counter_type>&, const time_stamp<counter_type>&);
};
template<typename counter_type>
inline time_span<counter_type> operator-(
const time_stamp<counter_type>& first, const time_stamp<counter_type>& second)
{
return time_span<counter_type>(first.m_stamp - second.m_stamp);
}
答案 1 :(得分:0)
尝试:
template<class counter_type>
class .... {
friend time_span<counter_type> operator-(const time_stamp<counter_type> &first, const time_stamp<counter_type> &second);
};
template<class counter_type>
time_span<counter_type> operator-(const time_stamp<counter_type> &first,
const time_stamp<counter_type> &second)
{
return time_span<counter_type>(first.m_stamp - second.m_stamp);
}