我有功能模板什么需要另一个功能(类)模板检查具体条件。这一切都适用于int或double,但是当我想为我的分数做这个工作时我不知道该怎么做。
template <class T, class F>
int HowManyF( int count, T *array, F function )
{
int howmany = 0;
for (int i = 0; i < count; i++)
{
if ( function(array[i]) )
howmany++;
}
return howmany;
}
template <class T>
class NotNegative
{
public:
T operator()(T arg);
};
template <class T>
T NotNegative<T>::operator()(T arg)
{
if (arg<0) return 0;
else return 1;
}
class Fraction{
public:
int numerator;
int denominator;
Fraction() {};
Fraction(int nume, int denom = 1);
Fraction operator += (const Fraction &u);
};
// this works
int ints[8] = {1,2,3,4,-5,6,-12,16};
howmany = HowManyF(8,ints,NotNegative());
cout << "NonNegative (ints) " << howmany << endl;
// this not - conditional expression of type 'Fraction' is illegal
// shows in line if ( function(array[i]) )
Fraction *tab = new Fraction[2];
tab[0] = Fraction(2, 4);
tab[1] = Fraction(5, 6);
howmany = HowManyF(2,tab,NotNegative<Fraction>());
cout << "NonNegative (fractions) " << howmany << endl;
我该怎么办?我需要将类模板更改为功能模板吗?我需要在Fraction类中添加一些运算符吗?我需要改变一种方法来检查变量是否<0?
你的谓词是错误的,特别是返回类型,它应该是:
template <class T>
class NotNegative
{
public:
bool operator()(T arg) const { return !(arg < 0); }
};
那么你可能需要Fraction
的专业化,或者在operator <
和Fraction
之间实现int
。