使用自定义类型专门化std :: complex时的模糊运算符

时间:2014-01-13 08:55:03

标签: c++ templates

我正在为无线通信仿真平台编写C ++代码。我们使用IT ++的定点算术库(http://itpp.sourceforge.net/4.3.1/group__fixed.html)。我们的目标是将浮点和定点算法包装在一个统一的类(名为num_c)中,并且可以为num_c类编写算法。

num_c类是从num_base_c派生的模板化类。 num_base_c类封装了一个IT ++ Fix(http://itpp.sourceforge.net/4.3.1/classitpp_1_1Fix.html)对象,看起来像这样(原谅我不能直接复制粘贴我的代码,因为它们在一个安全的网络中。我会尽量让代码列表尽可能准确):

class num_base_c
{
public:
    // Default constructor
    num_base_c(bool fix=false, double x=0.0, int w=itpp::MAX_WORDLEN, int s=0, itpp::emode e=itpp::TC, itpp::o_mode o=itpp::SAT, itpp::q_mode q=itpp::RND, itpp::Stat *ptr=0);
    // Other constructors ...

    // Conversion operator
    operator double() const;

    // Overloaded operators (including +=, -=, *=, -, +)

protected:
    bool m_flag_fixed;  // true means fixed point number
    double m_double;
    itpp::Fix m_fix;
};

num_c类看起来像这样:

// fix=true means fixed point value
template <bool fix, int w=16, int s=0, itpp::e_mode e=itpp::TC, itpp::o_mode o=itpp::SAT, itpp::q_mode q=itpp::RND>
class num_c : public num_base_c
{
public:
    // Default constructor
    explicit num_c(double x=0.0, itpp::Stat *ptr=0) : num_base_c(fix, x, w, s, e, o, q, ptr) {}
    // Other constructors ...
    // Constructor from int
    num_c(const int &x);

    // Different versions of overloaded operator = (assignment from num_base_c, itpp::fixrep, or int)
};

我想确定std :: complex的操作在使用num_c时是否能正常工作,所以我测试了以下内容:

using namespace std;
using namespace itpp;
complex< num_c<true, 16, 8, TC, SAT, RND> > c1(num_c<true, 16, 8, TC, SAT, RND>(1.3125, 0), num_c<true, 16, 8, TC, SAT, RND>(2.0625, 0));
num_c<true, 16, 8, TC, SAT, RND> n1(0, 0);
n1 = abs(c1);

在编译中,Visual Studio 2008会出现以下错误(摘录只有许多C2666错误中的一个): c:\ program files \ microsoft visual studio 9.0 \ vc \ include \ xcomplex(204):错误C2666:“operator&lt;”:2次重载有类似的转换 ... \ num_c_operators.h(16):可能是'bool operator&lt;(const num_base_c&amp;,const num_base_c&amp;)' 或'native C ++ operator&lt;(double,int)'

在我的num_c_operators.h中,在第16行,我声明了这个:

extern bool operator<(const num_base_c& op1, const num_base_c& op2);

我认为上面的运算符&lt;,加上“operator double()const”和“num_c(const int&amp; x)”是编译器试图匹配运算符&lt;(double,int)的原因。但是我确实需要重载运算符&lt;对于num_base_c。我还需要转换运算符从int加倍和构造函数(否则编译器将报告std :: complex的其他错误)。我不想写一个完全不同的复杂类(实际上IT ++提供了一个),因为现有的算法代码使用的是std :: complex。那么我该怎么做才能解决这个问题呢?

非常感谢! 彭

1 个答案:

答案 0 :(得分:0)

有解决冲突的方法:

  • 删除转换运算符
  • 没有构造函数执行隐式转换(make constructors explicit)
  • 或重载所有二元运算符。

如果你重载操作符,你可以这样做:

inline bool operator < (const num_base_c& a, const num_base_c& b) {
    return ...
}

template <typename U>
inline bool operator < (const num_base_c& a, const U& b) {
    return ...
}

template <typename U>
inline bool operator < (const U& a, const num_base_c& b) {
    return ...;
}