【发布时间】:2019-07-06 06:51:41
【问题描述】:
我有一个函数模板,它需要另一个函数(类)模板来检查特定条件。 这一切都适用于 int 或 doubles,但是当我想让它适用于我的分数时,我不知道该怎么做。
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 类中添加一些运算符吗?我需要改变一种方法来检查变量是否为
【问题讨论】:
-
“我该怎么办?” 给我们编译器错误verbatim ;)
-
“我有函数模板什么需要另一个函数(类)模板”注意术语,模板参数可以是模板本身(模板模板参数),但你的模板参数都是类型,不是模板
-
看看
NotNegative做了什么(arg<0)。Fraction是否支持该操作? -
另外,您的
HowManyF恰好是std::count_if的穷人版本。如果你把它写成学习材料,那很好,如果不是:知道并使用你的<algorithm>。 -
你的
NotNegative<T>::operator()(T arg)应该返回bool顺便说一句,谓词 (NotNegative) 最好用一个简单的 lambda 替换。
标签: c++ templates fractions negative-number