gpt4 book ai didi

c++ - 如何在模板类的成员中使用重载的原始 exp

转载 作者:行者123 更新时间:2023-11-30 02:46:32 27 4
gpt4 key购买 nike

我正在使用模板类 ( Pol<T> ) 来计算多项式,并希望使用成员函数 ( .exp() ) 将多项式 P 转换为其指数 e^P。
重载指数函数工作正常,编译器选择原始指数 exp(double)如果T = double和我自己的如果T=Pol<double> ,但在成员函数中我得到:

error: no matching function for call to ‘Pol<double>::exp(double&)’

我不能在成员函数中使用 std::exp,因为我使用的是多阶多项式,例如:

Pol< Pol< complex<double> > > P1

我可以使用重载指数来解决问题,但我不明白为什么它在成员内部是不可能的。

这是我的代码:

#include <iostream>
#include <math.h>
#include <vector>
using std::cout;
using std::endl;

template < class T>
class Pol;

template < class T >
const Pol< T > exp(const Pol< T >& P);

template < class T >
class Pol{
protected:
std::vector< T > Data;

public:
inline Pol():Data(1){}

inline const T operator[](int i)const{return Data[i];}
inline T& operator[](int i){return Data[i];}

Pol& exp();
};

template < class T >
const Pol< T > exp(const Pol< T >& P){
Pol< T > Erg(P);
Erg[0] = exp(P[0]); // works fine
return Erg;
}

template < class T >
Pol< T >& Pol< T >::exp(){
Data[0] = exp(Data[0]); // here appears the error
return *this;
}

int main() {
Pol<double> P1;

P1 = exp(P1); // this works
P1.exp(); // this enforces the error

cout << "P1[0]" << P1[0] << endl;
return 0;
}

最佳答案

编辑后,解决方案非常简单。如果您有成员函数,查找将忽略全局模板函数。您需要明确引用它:

Data[0] = ::exp(Data[0]);
// ^^ global scope

Live example

如果你想让编译器看到两者,你也可以使用:

using ::exp;
Data[0] = exp(Data[0]);

Live example

关于c++ - 如何在模板类的成员中使用重载的原始 exp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23479663/

27 4 0