我有一个函数模板,它使用另一个函数(类)模板来检查特定条件。 所有这些都可以用于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的方法?
答案 0 :(得分:0)
您的谓词是错误的,尤其是返回类型,应为:
template <class T>
class NotNegative
{
public:
bool operator()(T arg) const { return !(arg < 0); }
};
然后,您可能需要对Fraction
进行专业化处理,或者在operator <
和Fraction
之间实现int
。