模板函数可以采用另一个函数来检查有多少元素符合条件

问题描述 投票:0回答:1

我有功能模板什么需要另一个功能(类)模板检查具体条件。这一切都适用于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?

c++ templates fractions negative-number
1个回答
0
投票

你的谓词是错误的,特别是返回类型,它应该是:

template <class T>
class NotNegative
{
public:
    bool operator()(T arg) const { return !(arg < 0); }
};

那么你可能需要Fraction的专业化,或者在operator <Fraction之间实现int

© www.soinside.com 2019 - 2024. All rights reserved.