操作员+的模糊过载

时间:2011-07-26 13:54:18

标签: c++

Boost数学库中有多项式类:Boost polynomial class。我想通过添加新函数来扩展此类的功能,并使用继承,如下所示:

#ifndef POLY_HPP
#define POLY_HPP

#include <boost/math/tools/polynomial.hpp>

template <class T>
class Poly : public boost::math::tools::polynomial<T>{
public:

    Poly(const T* data, unsigned order) : boost::math::tools::polynomial<T>(data, order){

    }
};

#endif 

现在我声明了这个类的两个对象,我想添加它们:

    int a[3] = {2, 1, 3};
    Poly<int> poly(a, 2);
    int b[2] = {3, 1};
    Poly<int> poly2(b, 1);
    std::cout << (poly + poly2) << std::endl;

但是在赞美期间出现错误:

main.cpp: In function ‘int main()’:
main.cpp:28:26: error: ambiguous overload for ‘operator+’ in ‘poly + poly2’
/usr/local/include/boost/math/tools/polynomial.hpp:280:22: note: candidates are: boost::math::tools::polynomial<T> boost::math::tools::operator+(const U&, const boost::math::tools::polynomial<T>&) [with U = Poly<int>, T = int]
/usr/local/include/boost/math/tools/polynomial.hpp:256:22: note:                 boost::math::tools::polynomial<T> boost::math::tools::operator+(const boost::math::tools::polynomial<T>&, const U&) [with T = int, U = Poly<int>]
/usr/local/include/boost/math/tools/polynomial.hpp:232:22: note:                 boost::math::tools::polynomial<T> boost::math::tools::operator+(const boost::math::tools::polynomial<T>&, const boost::math::tools::polynomial<T>&) [with T = int]
make[2]: Leaving

为operator +定义了三个重载函数。我认为应该采取:

boost::math::tools::polynomial<T> boost::math::tools::operator+(const boost::math::tools::polynomial<T>&, const boost::math::tools::polynomial<T>&)

因为Poly类是从Boost多项式继承的,并且参数传递得最好,但是它不会发生。如何在没有operator +?

的显式新定义的情况下添加两个Poly类对象

1 个答案:

答案 0 :(得分:2)

据我所知,这是不可能的,你需要像

这样的东西
template <class T>
Poly<T> operator + (const Poly<T>& a, const Poly<T>& b) {
    return Poly<T>(static_cast< boost::math::tools::polynomial<T> >(a) +
                   static_cast< boost::math::tools::polynomial<T> >(b));
}

消除调用的歧义(需要在您的类中boost::math::tools::polynomial<T>Poly<T>的适当转换构造函数...)